命名空间
变体
操作

std::jthread::detach

来自 cppreference.cn
< 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)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(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

[编辑] 异常

如果 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