
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements