std::jthread::detach
來自 cppreference.com
void detach(); |
(C++20 起) | |
將執行執行緒與 jthread 物件分離,允許其獨立繼續執行。一旦執行緒退出,所有分配的資源將被釋放。
呼叫 detach
後,*this 不再擁有任何執行緒。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
(無)
[編輯] 後置條件
joinable 為 false。
[編輯] 異常
如果 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
|