名稱空間
變體
操作

std::jthread::detach

來自 cppreference.com
< cpp‎ | thread‎ | jthread
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
void detach();
(C++20 起)

將執行執行緒與 jthread 物件分離,允許其獨立繼續執行。一旦執行緒退出,所有分配的資源將被釋放。

呼叫 detach 後,*this 不再擁有任何執行緒。

目錄

[編輯] 引數

(無)

[編輯] 返回值

(無)

[編輯] 後置條件

joinablefalse

[編輯] 異常

如果 joinable() == false 或發生錯誤,則丟擲 std::system_error

[編輯] 示例

#include <chrono>
#include <iostream>
#include <thread>
 
void independentThread() 
{
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}
 
void threadCaller() 
{
    std::cout << "Starting thread caller.\n";
    std::jthread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}
 
int main() 
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

可能的輸出

Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.

[編輯] 參考

  • C++23 標準 (ISO/IEC 14882:2024)
  • 33.4.4.3 成員 [thread.jthread.mem]
  • C++20 標準 (ISO/IEC 14882:2020)
  • 32.4.3.2 成員 [thread.jthread.mem]

[編輯] 另請參閱

等待執行緒完成其執行
(public member function) [編輯]
檢查執行緒是否可join,即是否可能在並行上下文中執行
(public member function) [編輯]
C documentation for thrd_detach