<thread>

公共成员函数
<thread>

std::thread::detach

void detach();
分离线程
将对象所代表的线程与调用线程分离,允许它们独立执行。

两个线程都会继续执行,既不阻塞也不进行任何同步。请注意,当其中一个线程结束执行时,其资源将被释放。

调用此函数后,thread 对象将变为joinable状态,可以安全地被销毁

参数



返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
void pause_thread(int n) 
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}
 
int main() 
{
  std::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1).detach();
  std::thread (pause_thread,2).detach();
  std::thread (pause_thread,3).detach();
  std::cout << "Done spawning threads.\n";

  std::cout << "(the main thread will now pause for 5 seconds)\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}

输出(5秒后)
Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended


数据竞争

对象被修改。

异常安全

基本保证:如果此成员函数抛出异常,thread 对象将保持在有效状态。

如果调用失败,将抛出system_error 异常
异常类型错误条件描述
system_errorerrc::invalid_argumentthread 对象不是joinable
system_errorerrc::no_such_processthread 对象无效

另见