C++ Poco - 如何向特定线程发送通知/消息?

C++ Poco - How to send a notification/message to a specific thread?

本文关键字:通知 消息 线程 Poco C++      更新时间:2023-10-16

我在下面有这段代码。

我有两个不同的线程:FooBar。 在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上创建一个sourcedestination。 但这给我带来了两个问题:

1 - 如果我需要为邮件创建自己的过滤,如何只查看邮件而不将其从队列中删除?例如:Thread A需要向Thread B发送消息,但Thread C首先捕获它。所以Thread C只需要偷看目的地......如果不是针对他们,则不会从队列中删除消息。

2 -POCO上没有办法自动执行此操作吗?就像告诉通知仅适用于该特定线程一样?

你可以选择Poco Events,而不是通知队列。通过使用两个不同的事件,EventB 可用于通知线程 B,而 EventC 可用于通知 ThreadC。