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<void> 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<void> exitSignal;

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

std::future<void> 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 <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
   std::cout << "Starting the thread" << std::endl;
   while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){
      std::cout << "Executing the thread....." << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds
   }
   std::cout << "Thread Terminated" << std::endl;
}
main(){
   std::promise<void> signal_exit; //create promise object
   std::future<void> 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 << "Threads will be stopped soon...." << std::endl;
   signal_exit.set_value(); //set value into promise
   my_thread.join(); //join the thread with the main thread
   std::cout << "Doing task in main function" << std::endl;
}

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: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements