In this article we will discuss how to stop or terminate a thread in C++11.

C++11 does not provides a direct method to stop a running thread and that’s because that thread might have some resources to release or close before exit i.e.

  • What if a thread has acquired a lock and we kill that thread suddenly, then who’s gonna release that lock ?
  • What if a thread has opened a file to write the text and we stopped that thread, then who’s gonna close that file ?
  • What if thread has allocated memory on heap and before it could delete that memory, we stopped the thread. Then who’s gonna prevent that memory leak.

Therefore there is no direct function to close the thread. But we can notify the thread to exit and we can implement out thread in a such a way that after some interval or at some checkpoints it should check, if I am requested to exit or not. If yes then it should exit gracefully , by releasing all the resources.

Stopping a Thread using std::future<>

We can pass a std::future<void> object to thread and thread should exit when value in future is available. As, we want to only signal the thread and not actually passing any value in that signal, so we will can use future object of type void.

Let’s create a promise object of type void in main function i.e.

Now, fetch the associated future object from this promise in main function i.e.

Now in main function while creating the thread, pass the future object to the thread function i.e.

Inside the thread, we are doing some Work and keep on checking that if thread has been requested to exit i.e. value in future is available or not.

As soon as we set value in promise object from main function, value in future object will available in thread function i.e.

Complete example is as follows,


Creating a Stoppable Task

Creating promise and future object every time, when we want to create task that can be stopped, is a repeating task.
Let’s avoid that by creating a Stoppable class that provide all this functionality in object oriented manner.

Stoppable class that encapsulate the promise and future object

We just need to extend this class in our task class and provide definition for run() function, which will like our thread function i.e.

Now lets see how to use this Stoppable task in main function i.e.

Learn more about multithreading in C++11 / 14

Complete example is as follows,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.