<thread>

<thread>

std::thread

class thread;
執行緒
表示獨立執行緒的類

所謂執行緒,是指在多執行緒環境中,可以與其它指令序列併發執行,同時共享相同地址空間的指令序列。

一個已初始化的thread物件代表一個活動的執行緒;這樣的thread物件是可join的,並且有一個唯一的執行緒id

預設構造的(未初始化的)thread物件是不可join的,並且其執行緒id對所有不可join的執行緒都是公共的。

一個可join的執行緒,如果被移動賦值,或者對其呼叫了joindetach,則會變為不可join的

成員型別


成員函式


非成員過載


示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
 
void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

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

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

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

  return 0;
}

輸出
main, foo and bar now execute concurrently...
foo and bar completed.