C++ 庫 - <thread>



介紹

執行緒是在多執行緒環境中可以與其他類似序列併發執行的指令序列,同時共享同一個地址空間。

成員型別

序號 成員型別及描述
1 id

執行緒ID。

2 原生控制代碼型別

原生控制代碼型別。

成員函式

序號 成員函式及描述
1 (建構函式)

用於構造執行緒。

2 (解構函式)

用於析構執行緒。

3 operator=

移動賦值執行緒。

4 get_id

用於獲取執行緒ID。

5 joinable

用於檢查是否可連線。

6 join

用於連線執行緒。

7 detach

用於分離執行緒。

8 swap

用於交換執行緒。

9 native_handle

用於獲取原生控制代碼。

10 hardware_concurrency [靜態]

用於檢測硬體併發性。

非成員過載

序號 非成員過載及描述
1 swap (thread)

用於交換執行緒。

示例

以下為 std::thread 的示例。

#include <iostream>
#include <thread>

void foo() {
   std::cout << " foo is executing concurrently...\n";
}

void bar(int x) {
   std::cout << " bar is executing concurrently...\n";
}

int main() {
   std::thread first (foo);
   std::thread second (bar,0);

   std::cout << "main, foo and bar now execute concurrently...\n";

   first.join();
   second.join();

   std::cout << "foo and bar completed.\n";

   return 0;
}

輸出應如下所示:

main, foo and bar now execute concurrently...
 bar is executing concurrently...
 foo is executing concurrently...
foo and bar completed.
廣告
© . All rights reserved.