名前空間
変種
操作

std::jthread::detach

From 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)
future
(C++11)
(C++11)
(C++11)
(C++11)
安全なメモリ解放 (Safe Reclamation)
(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です。

[編集] 例外

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について
English 日本語 中文(简体) 中文(繁體)