4

I am using POCO default thread pool to start a event receiver thread which would listen for events. Once the event is received I need to process that event in a separate thread.

Here is what I am trying to do but i couldn't start the event processor in a new thread. The application hangs when i try to do so. I tried event printing the thread pool stats but the application hangs the moment I call default thread pool.

#include "Poco/ThreadPool.h"
#include "Poco/Runnable.h"
#include <iostream>
#include <thread>

class EventProcessor : public Poco::Runnable
{
public:
    void run()
    {
        // Event shall be processed here 
    }      
}; 

class EventReceiver : public Poco::Runnable
{
public:
    void run()
    {    
        // App hangs when i try to do this
        std::cout  << "Capacity: " <<   Poco::ThreadPool::defaultPool().capacity() << std::endl;
        
        EventProcessor eventProcessor;   
        Poco::ThreadPool::defaultPool().start(eventProcessor);
    }
};

int main(int argc, char** argv)
{
    EventReceiver eventReceiver;
    Poco::ThreadPool::defaultPool().start(eventReceiver);
    Poco::ThreadPool::defaultPool().joinAll();
    return 0;
}

1 Answers1

1

You are starting a thread with a reference to stack object, which is destroyed when the run() function returns; that creates undefined behavior.

A better way of doing this would be to have two threads (or tasks) that share a NotificationQueue. When you receive event, you enqueue notification to the queue in the receiver thread. The processing thread dequeues events and processes them. NotificationQueue is thread-safe, so no external locking is required between enqueuing and dequeuing.

You can see how to implement that in the NotificationQueue example; you will probably want the events enqueuing to happen in a thread other than main.

Alex
  • 5,159
  • 4
  • 25
  • 33