<thread>

公共成員函式
<thread>

std::thread::detach

void detach();
分離執行緒
將物件所代表的執行緒與呼叫執行緒分離,允許它們獨立執行。

兩個執行緒都會繼續執行,既不阻塞也不進行任何同步。請注意,當其中一個執行緒結束執行時,其資源將被釋放。

呼叫此函式後,thread 物件將變為joinable狀態,可以安全地被銷燬

引數



返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
void pause_thread(int n) 
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}
 
int main() 
{
  std::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1).detach();
  std::thread (pause_thread,2).detach();
  std::thread (pause_thread,3).detach();
  std::cout << "Done spawning threads.\n";

  std::cout << "(the main thread will now pause for 5 seconds)\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}

輸出(5秒後)
Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended


資料競爭

物件被修改。

異常安全

基本保證:如果此成員函式丟擲異常,thread 物件將保持在有效狀態。

如果呼叫失敗,將丟擲system_error 異常
異常型別錯誤條件描述
system_errorerrc::invalid_argumentthread 物件不是joinable
system_errorerrc::no_such_processthread 物件無效

另見