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.
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.
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.
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.
In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With