join()与detach()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48



#include <iostream>
#include <thread>
using namespace std;

void B_work()
{
int i=0;
while(i<20)
{
cout<<"B"<<i<<endl;
i++;
}
}

void A_work()
{
int i=0;
thread b(B_work);
b.detach();
while(i<2)
{
cout<<"A"<<endl;
i++;
}
}

void thin()
{
thread a(A_work);

}

int main() //主线程
{
thin();
int i=100;
while(i>0)
{
cout<<"c"<<endl;
i--;
}
return 0;
}


执行以上代码,可以发现:

  1. 在创造线程之后如果没有决定让其join或detach,那么std::thread 被释放时,新创造的线程所关联的线程会被强制terminate,然后操作系统回收程序资源(慢)。但在操作系统回收整个程序的资源之前,线程还是会继续执行一会。
  2. 使用detach()后,创造的std::thread 将会与当前线程分离分离并继续执行,并且在原线程释放掉std::thread 内存也将继续执行,当main()线程结束,那么运行时库将会立即回收全部的线程资源(快)。

a线程被创立后其没有detach(),而b调用detach(),std::thread a被main()线程释放后立即terminate了整个程序,但此时其线程资源(线程的栈空间)还未被操作系统回收,因此b线程还会继续执行。

a线程被创立后其detach(),而b不调用detach():当b线程资源被释放时,main() 线程可以就继续执行但a线程报terminate中止。那么只有等main()执行结束操作系统才将b线程的资源回收,期间b线程一直在执行也就变成了野线程。

生产者、消费者

条件变量的伪唤醒

链接:https://blog.csdn.net/Wyf_Fj/article/details/126505728

先上锁还是先发信号的问题

链接:https://blog.csdn.net/gqtcgq/article/details/52301749