如何終止 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