一个简单的Poco C++ 多线程与通知队列

#include 
#include "Poco/Thread.h"
#include "Poco/NotificationQueue.h"

using namespace std;

class MyNotification : public Poco::Notification
{
public:
    MyNotification(const string& msg) : _msg(msg) {}
    const string& message() const { return _msg; }
private:
    string _msg;
};

class MyRunnable : public Poco::Runnable
{
public:
    MyRunnable(Poco::NotificationQueue& queue) : _queue(queue) {}

    void run()
    {
        while (true)
        {
            Poco::AutoPtr pNf = static_cast(_queue.waitDequeueNotification());
            if (pNf)
            {
                cout << pNf->message() << " (thread ID: " << Poco::Thread::currentTid() << ")" << endl;
            }
        }
    }

private:
    Poco::NotificationQueue& _queue;
};

int main()
{
    Poco::NotificationQueue queue;
    MyRunnable r1(queue), r2(queue);
    Poco::Thread t1, t2;

    t1.start(r1);
    t2.start(r2);

    for (int i = 0; i < 10; i++)
    {
        string msg = "Message #" + to_string(i);
        Poco::AutoPtr pNf = new MyNotification(msg);
        queue.enqueueNotification(pNf);
        Poco::Thread::sleep(1000);
    }

    t1.join();
    t2.join();

    return 0;
}

运行结果:

一个简单的Poco C++ 多线程与通知队列_第1张图片

 

你可能感兴趣的:(c++)