std::thread::detach

来自cppreference.com
< cpp‎ | thread‎ | thread

 
 
线程支持库
线程
(C++11)
(C++20)
(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++11)
(C++11)
条件变量
(C++11)
信号量
闩与屏障
(C++20)
(C++20)
future
(C++11)
(C++11)
(C++11)
(C++11)
 
 
void detach();
(C++11 起)

从 thread 对象分离执行线程,允许执行独立地持续。一旦该线程退出,则释放任何分配的资源。

调用 detach*this 不再占有任何线程。

参数

(无)

返回值

(无)

后条件

joinablefalse

异常

joinable() == false 或出现任何错误则为 std::system_error

示例

#include <iostream>
#include <chrono>
#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::thread 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++20 标准(ISO/IEC 14882:2020):
  • 32.4.2.5 Members [thread.thread.member]
  • C++17 标准(ISO/IEC 14882:2017):
  • 33.3.2.5 thread members [thread.thread.member]
  • C++14 标准(ISO/IEC 14882:2014):
  • 30.3.1.5 thread members [thread.thread.member]
  • C++11 标准(ISO/IEC 14882:2011):
  • 30.3.1.5 thread members [thread.thread.member]

参阅

等待线程完成其执行
(公开成员函数)
检查线程是否可合并,即潜在地运行于平行环境中
(公开成员函数)