C++ 庫 - <stop_token>



C++20 中的<stop_token> 標頭檔案引入了一種取消執行緒和非同步操作的機制。它與 `std::stop_source` 配合使用,`std::stop_source` 負責生成停止請求。

這些用於實現響應式系統,該系統可以停止操作,而無需強制終止或複雜的訊號機制。

包含 <stop_token> 標頭檔案

要在 C++ 程式中包含 <stop_token> 標頭檔案,可以使用以下語法。

#include <stop_token>

<stop_token> 標頭檔案的函式

以下是 <stop_token> 標頭檔案中所有函式的列表。

序號 函式及描述
1 operator=

它賦值 `stop_token` 物件。

2 swap

它交換兩個 `stop_token` 物件。

3 stop_requested

它檢查關聯的停止狀態是否已請求停止。

4 stop_possible

它檢查關聯的停止狀態是否可以請求停止。

5 get_token

它返回關聯停止狀態的 `stop_token`。

使用停止令牌的多執行緒

在下面的示例中,我們將使用 `std::stop_source` 來控制多個執行緒。

#include <iostream>
#include <thread>
#include <stop_token>
#include <chrono>
void a(int id, std::stop_token b) {
   while (!b.stop_requested()) {
      std::cout << "A " << id << " Is Working.." << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(600));
   }
   std::cout << "A " << id << " Is Cancelled.." << std::endl;
}
int main() {
   std::stop_source x;
   std::thread x1(a, 1, x.get_token());
   std::thread x2(a, 2, x.get_token());
   std::this_thread::sleep_for(std::chrono::seconds(2));
   x.request_stop();
   x1.join();
   x2.join();
   return 0;
}

輸出

以上程式碼的輸出如下:

A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Working..
A 1 Is Working..
A 2 Is Cancelled..
A 1 Is Cancelled..
廣告