Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
To create one promise object, we have to follow this syntax −
std::promiseexitSignal;
Now fetch the associated future object from this created promise object in main function −
std::futurefutureObj = 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
Advertisements
