如何终止 C++11 中的线程?
在这里,我们将学习如何在 C++11 中终止线程。C++11 没有终止线程的直接方法。
可以使用 std::future<void> 进行线程,并且当 Future 中的值可用时,它应该退出。如果我们想向线程发送信号,但不发送实际的值,我们可以传递 void 类型对象。
要创建一个 promise 对象,我们必须遵循以下语法 −
std::promise<void> exitSignal;
现在从这个创建的 promise 对象中获取关联的 future 对象 −
std::future<void> futureObj = exitSignal.get_future();
现在在创建线程时传递主函数,传递 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP