C++ C++;Poco-如何向特定线程发送通知/消息?
我有下面的代码 我有两个不同的线程:C++ C++;Poco-如何向特定线程发送通知/消息?,c++,multithreading,messaging,poco-libraries,C++,Multithreading,Messaging,Poco Libraries,我有下面的代码 我有两个不同的线程: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/Aut
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;
}
我知道我可以像过滤器一样在消息类
上创建源
和目标
。
但这给我带来了两个问题:
1-如果我需要为邮件创建自己的筛选,我如何在不将其从队列中删除的情况下查看邮件?例如:线程A
需要向线程B
发送消息,但是线程C
首先捕获消息。因此线程C
只需窥视目标。。。如果不适合他们,则不会从队列中删除消息
2-在
POCO
上是否已经有任何方法可以自动执行此操作?就像告诉我通知只针对那个特定的线程一样?为什么不针对不同的线程使用不同的队列呢?我猜是因为如果我有一个线程可以向100个不同的线程发送通知,我必须传递所有通知引用才能告诉我需要发送哪个线程。我认为这里的最佳实践是只对所有线程使用一个通知队列。我想错了吗?谢谢你的帮助。
received from Foo: start
received from Foo: start
received from Bar: start
received from Bar: start
received from Foo: start