Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 event loop with thread safe queue

I want to create an event loop class that will run on it's own thread, support adding of tasks as std::functions and execute them. For this, I am using the SafeQueue from here: https://stackoverflow.com/a/16075550/1069662

class EventLoop
{
public:
typedef std::function<void()> Task;

EventLoop(){ stop=false; }

void add_task(Task t) { queue.enqueue(t); }

void start();

void stop() { stop = true; }

private:
    SafeQueue<Task> queue;
    bool stop;
};

void EventLoop::start()
{
    while (!stop) {
        Task t = queue.dequeue(); // Blocking call
        if (!stop) {
            t();
        }
    }    

    cout << "Exit Loop";
}

Then, you would use it like this:

EventLoop loop;
std::thread t(&EventLoop::start, &loop);

loop.add_task(myTask);
// do smth else

loop.stop();
t.join();

My question is: how to stop gracefully the thread ? Here stop cannot exit the loop because of the blocking queue call.

like image 403
yandreiy Avatar asked Oct 18 '14 16:10

yandreiy


People also ask

How do I make a queue thread-safe?

Thread safe means that you have to isolate any shared data. Here your shared data is the pointer to the queue.So , in general , any time you have operations on the queue you need to protect queue and prevent multiple threads reach your queue at the same time. One good way is to implement Condition Variables.

Are queues thread-safe?

The Queue module provides a FIFO implementation suitable for multi-threaded programming. It can be used to pass messages or other data between producer and consumer threads safely.

Are STL containers thread-safe?

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.

What is CPP event loop?

In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program.


1 Answers

Queue up a 'poison pill' stop task. That unblocks the queue wait and either directly requests the thread to clean up and exit or allows the consumer thread to check a 'stop' boolean.

That's assuming you need to stop the threads/task at all before the app terminates. I usually try to not do that, if I can get away with it.

like image 132
Martin James Avatar answered Sep 23 '22 15:09

Martin James