How to terminate a thread in C++
Hello fellow learners! In this tutorial, we will learn how we can terminate a thread in C++.
C++11 does not have a direct method to terminate a thread because it has some resources to close before exit. The thread can be stopped using std::future<void>. We only want to see the output & no need to pass any values so future<void> is apt for the same.
C++ Code: Terminating a thread
Read the comments in the code for better understanding.
#include <thread> #include <iostream> #include <chrono> #include <future> void threadFunction(std::future<void> futureObj) { std::cout << "Starting the thread" << std::endl; while (futureObj.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout) { std::cout << "work done" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } std::cout << "Ending Thread" << std::endl; } int main() { std::promise<void> exitSignal; // Create a std::promise object std::future<void> futureObj = exitSignal.get_future();//Fetch std::future object associated with promise std::thread th(&threadFunction, std::move(futureObj));// Starting Thread & move the future object in lambda function by reference std::this_thread::sleep_for(std::chrono::seconds(10)); //Waiting for 10 seconds std::cout << "Asking the thread to stop" << std::endl; exitSignal.set_value(); //Set the value th.join(); //Waiting for thread to be joined. std::cout << "Exit the Main Function" << std::endl; return 0; }
Output:
Starting the thread work done work done work done work done work done work done work done work done work done work done Asking the thread to stop Ending Thread Exit the Main Function
Explanation of the code:
We will create a promise object in the main function. Next, we will be going to extract the future objects from this promise in the main function. Now we will pass the future object to the thread object to thread function in the main function. Inside the thread the work is been done & we will keep checking the thread if it is instructed to exit ie. value in future is available or not. As soon as object value is set from the main function value in future object will be available in the thread.
Hope this tutorial would be helpful!
Leave a Reply