Namespaces
Variants

std::jthread:: detach

From cppreference.net

Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
void detach ( ) ;
(C++20以降)

jthreadオブジェクトから実行スレッドを分離し、実行が独立して継続することを許可します。割り当てられたリソースは、スレッドが終了すると解放されます。

detach を呼び出した後、 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 メンバー [thread.jthread.mem]
  • C++20規格 (ISO/IEC 14882:2020):
  • 32.4.3.2 メンバー [thread.jthread.mem]

関連項目

スレッドの実行終了を待機する
(公開メンバ関数)
スレッドが結合可能かどうか、すなわち並列コンテキストで実行されている可能性があるかをチェックする
(公開メンバ関数)
Cドキュメント for thrd_detach