在这里,我们将看到如何在C ++ 11中终止线程。C ++ 11没有直接方法来终止线程。
std::future <void>可以用于线程,并且当将来的值可用时应该退出。如果我们要向线程发送信号,但不发送实际值,则可以传递void类型的对象。
要创建一个Promise对象,我们必须遵循以下语法-
std::promise<void> exitSignal;
现在从主函数中此创建的Promise对象中获取关联的Future对象-
std::future<void> futureObj = exitSignal.get_future();
现在在创建线程时传递main函数,传递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