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

时间:2018-09-04 15:21:24

标签: c++ multithreading messaging poco-libraries

我下面有这段代码。

我有两个不同的线程:FooBar。 我想在main()上向Foo线程发送消息。为此,我正在使用NotificationQueue库中的POCO

#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

我知道我可以像使用过滤器一样在source上创建destinationmessage class。 但这给我带来两个问题:

1-如果我需要为消息创建自己的过滤器,如何在不将消息从队列中删除的情况下偷看消息?例如:Thread A需要发送一条消息到Thread B,但是Thread C首先捕获它。因此,Thread C只需要窥视目的地……如果不是目的地,则不会从队列中删除消息。

2-{{​​1}}上已经没有任何方法可以自动进行此操作?就像告诉该通知仅针对该特定线程一样?

0 个答案:

没有答案