I want to create an event loop class that will run its own thread on it, support adding tasks as std::functionswell as execute them. For this, I am using SafeQueue from here: https://stackoverflow.com/a/316618/
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();
if (!stop) {
t();
}
}
cout << "Exit Loop";
}
Then you will use it as follows:
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 the grace of the stream? Here stop cannot exit the loop due to a call to the lock queue.
source
share