A simple method for controlling the while-loop of a thread. This principle also allows easy communication with the thread.

How to stop a thread.

It is a nice idea to create a functor (overload operator()) and pass a functor object to a thread. The operator()() (line 9) should generally contain a while loop (event loop)(line 10). To be able to stop the while loop from the outside, one can use a member variable of the functor, e.g. bool IsStopped or bool IsRunning (line 15). The loop would then look like this


Another thread (e.g. the main thread) could then set the flag to true (or false) (line 23) and this will end the while loop.

In order to make this work, the functor object has to be passed as a reference to the thread (line 20).


If you need more sophisticated communication between threads, you should use the buffer or channel which are described in separate posts.