C++ Poco - 如何向特定线程发送通知/消息?
C++ Poco - How to send a notification/message to a specific thread?
我在下面有这段代码。
我有两个不同的线程:Foo
和Bar
。 在main()
,我想向Foo
线程发送消息。为此,我使用的是POCO
库中的NotificationQueue
。
#include <iostream>
#include "Poco/Notification.h"
#include "Poco/NotificationQueue.h"
#include "Poco/ThreadPool.h"
#include "Poco/Runnable.h"
#include "Poco/AutoPtr.h"
using Poco::Notification;
using Poco::NotificationQueue;
using Poco::ThreadPool;
using Poco::Runnable;
using Poco::AutoPtr;
class Message : public Notification
{
public:
Message(std::string msg)
: mMsg(msg)
{
}
std::string getMsg() const
{
return mMsg;
}
private:
std::string mMsg;
};
class Foo: public Runnable
{
public:
Foo(NotificationQueue& queue) : mQueue(queue) {}
void run()
{
AutoPtr<Notification> notification(mQueue.waitDequeueNotification());
while (notification)
{
Message* msg = dynamic_cast<Message*>(notification.get());
if (msg)
{
std::cout << "received from Foo: " << msg->getMsg() << std::endl;
}
notification = mQueue.waitDequeueNotification();
}
}
private:
NotificationQueue & mQueue;
};
class Bar: public Runnable
{
public:
Bar(NotificationQueue& queue) : mQueue(queue) {}
void run()
{
AutoPtr<Notification> notification(mQueue.waitDequeueNotification());
while (notification)
{
Message* msg = dynamic_cast<Message*>(notification.get());
if (msg)
{
std::cout << "received from Bar: " << msg->getMsg() << std::endl;
}
notification = mQueue.waitDequeueNotification();
}
}
private:
NotificationQueue & mQueue;
};
int main(int argc, char** argv)
{
NotificationQueue queue;
Foo foo(queue);
Bar bar(queue);
ThreadPool::defaultPool().start(foo);
ThreadPool::defaultPool().start(bar);
queue.enqueueNotification(new Message(std::string("start"))); //I want to send this message to Foo!!!
while (!queue.empty())
{
Poco::Thread::sleep(100);
}
queue.wakeUpAll();
ThreadPool::defaultPool().joinAll();
return 0;
}
我已经运行了几次代码,我可以看到有时线程Foo
首先捕获消息,但有时它是Bar
线程。
运行5次后输出:
received from Foo: start
received from Foo: start
received from Bar: start
received from Bar: start
received from Foo: start
我知道我可以像过滤器一样在message class
上创建一个source
和destination
。 但这给我带来了两个问题:
1 - 如果我需要为邮件创建自己的过滤,如何只查看邮件而不将其从队列中删除?例如:Thread A
需要向Thread B
发送消息,但Thread C
首先捕获它。所以Thread C
只需要偷看目的地......如果不是针对他们,则不会从队列中删除消息。
2 -POCO
上没有办法自动执行此操作吗?就像告诉通知仅适用于该特定线程一样?
你可以选择Poco Events,而不是通知队列。通过使用两个不同的事件,EventB 可用于通知线程 B,而 EventC 可用于通知 ThreadC。
相关文章:
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何通过参数抛出错误消息
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- 函数如何通知用户它基于函数原型抛出异常?
- C++入门 5 版:类消息和文件夹
- C++ Poco - 如何向特定线程发送通知/消息?
- Win32 中是否有一条消息或通知来检测用户何时更改区域设置?
- WinAPI设备通知-未进入消息循环
- 如何在窗口提示对话框(即错误消息)时获取通知
- ZeroMQ是否有数据到达时的通知/回调事件/消息
- 仅显示消息窗口中的电源状态更改通知
- 从主框架到Dockpane对话框的消息通知
- 屏幕分辨率更改通知消息