【发布时间】:2018-09-04 15:21:24
【问题描述】:
我在下面有这段代码。
我有两个不同的线程: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 上没有任何方法可以自动完成此操作吗?就像告诉该通知仅适用于该特定线程?
【问题讨论】:
-
为什么不为不同的线程使用不同的队列?
-
我猜是因为如果我有一个线程可以向 100 个不同的线程发送通知,我必须传递所有通知引用才能知道我需要发送到哪个线程。我认为这里的最佳做法是仅对所有线程使用一个通知队列。我想错了吗?感谢您的帮助。
标签: c++ multithreading messaging poco-libraries