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 后, * 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 文档 关于 thrd_detach