C ++ 11 thread safety event loop

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(); // Blocking call
        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.

+4
source share
2 answers

" ". , "stop".

, / , . , .

+4

: , . :

class EventLoop {

// ...

    class stopexception {};

// ...


    void stop()
    {
          add_task(
               // Boring function that throws a stopexception
          );
    }
};

void EventLoop::start()
{
    try {
        while (1)
        {
            Task t = queue.dequeue(); // Blocking call
            t();
        }
    } catch (const stopexception &e)
    {
        cout << "Exit Loop";
    }
}

, , , , , EventLoop , stop() , .

+1

All Articles