std::jthread::detach
From cppreference.com
| void detach(); |
(C++20以降) | |
実行スレッドをjthreadオブジェクトから切り離し、スレッドが独立して実行を継続できるようにします。割り当てられたリソースは、スレッドが終了すると解放されます。
detachを呼び出した後、*thisはもはやスレッドを所有しません。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
(なし)
[編集] 後条件
joinableはfalseです。
[編集] 例外
std::system_error joinable() = falseの場合、またはエラーが発生した場合。
[編集] 例
このコードを実行
#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 Members [thread.jthread.mem]
- C++20 standard (ISO/IEC 14882:2020)
- 32.4.3.2 Members [thread.jthread.mem]
[編集] 関連項目
| スレッドが実行を完了するまで待機する (public member function) | |
| スレッドが join 可能か、すなわち並行コンテキストで実行されている可能性があるかをチェックする (public member function) | |
| C言語のドキュメント thrd_detachについて
| |