std::thread::detach

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.

引用

  • 30.3.1.5 thread members [thread.thread.member]

参阅

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

版本历史

  • (当前 | 先前 2017年8月25日 (五) 06:17Fruderica讨论 | 贡献. . (1,559字节) (+88). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:35P12bot讨论 | 贡献 . . (1,471字节) (-38). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 18:33P12bot讨论 | 贡献 . . (1,509字节) (+257). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,252字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,252字节) (+1,252). . (Translated from the English version using Google Translate)