C++ Reference 之 Thread Class

C++ 中提供了 Thread(用來表示分別執行的線程的類) 線程類.

在多線程環境中,一個執行的線程是一個能被與其他線程的指令序列併發執行的指令序列,它們共享一個地址空間。
一個初始化過的 thread 對象表示一個有效的執行線程; 這樣的線程是 joinable 並且有一個唯一的 thread id。

一個默認構造的(沒有被初始化的) thread 對象是 non-joinable , 它的 thread id 與所有 non-joinable 的線程共用。
一個 joinable 線程被 moved 之後或者調用 join 或 detach 之後就變爲 non-joinable。

成員類型:

id Thread id(public member type)
native_handle_type Native handle type(public member type)

成員函數

構造函數
析構函數
operator= Move-assign thread(public)
get_id 獲取 thread id(public)
joinable 檢查線程是否 joinable(public)
join Join thread(public)
detach 分離 thread(public)
swap 交換 thread(public)
native_handle 獲得 native handle(public)
hardware_concurrency[static] 檢查硬件併發性(public static)

非成員重載函數

swap(thread) 交換 threads (function)

Example

// thread example
#include <iostream>
#include <thread>

void foo() {
  std::cout << "foo" << std::endl;
}

void bar(int x) {
  std::cout << "bar int x" << std::endl;
}

int main() {
  // 創建一個調用 foo 接口的線程。
  std::thread first(foo);
  // 創建一個調用 bar 接口 參數爲 int 的線程。
  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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章