How do I terminate a thread in C++11?

Here we will see, how to terminate the threads in C++11. The C++11 does not have direct method to terminate the threads.

The std::future can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.

To create one promise object, we have to follow this syntax −

std::promise exitSignal;

Now fetch the associated future object from this created promise object in main function −

std::future futureObj = exitSignal.get_future();

Now pass the main function while creating the thread, pass the future object −

std::thread th(&threadFunction, std::move(futureObj));

Example

#include 
#include 
#include 
#include 
#include 
using namespace std;
void threadFunction(std::future future){
   std::cout  signal_exit; //create promise object
   std::future future = signal_exit.get_future();//create future objects
   std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
   std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
   std::cout 

Output

Starting the thread
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Threads will be stopped soon....
Thread Terminated
Doing task in main function
Updated on: 2019-07-30T22:30:26+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements