यहां हम देखेंगे कि C++11 में थ्रेड्स को कैसे समाप्त किया जाए। C++11 में थ्रेड्स को समाप्त करने की सीधी विधि नहीं है।
Std::future
एक वादा वस्तु बनाने के लिए, हमें इस सिंटैक्स का पालन करना होगा -
std::promise<void> exitSignal;
अब संबंधित भविष्य की वस्तु को मुख्य समारोह में इस निर्मित वादा वस्तु से प्राप्त करें -
std::future<void> futureObj = exitSignal.get_future();
अब थ्रेड बनाते समय मुख्य कार्य को पास करें, भविष्य की वस्तु को पास करें -
std::thread th(&threadFunction, std::move(futureObj));
उदाहरण
#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;
} आउटपुट
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