C++ thread

一个实验

  • 使用join
    在join位置阻塞主线程
  • 使用detach
    不阻塞主线程(即使线程没执行完,一旦主线程结束则该线程亦结束)
  • 不对线程控制
    主线程退出时会弹错:
1
2
  terminate called without an active exception
[1] 18090 abort ./bin/concurrency

If neither join or detach is called with a std::thread object that has associated executing thread then during that object’s destruct-or it will terminate the program.
Because inside the destruct-or it checks if Thread is Still Join-able then Terminate the program i.e.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
void operator()()
{
std::cout<<"Worker Thread "<<std::endl;
}
};
int main()
{
std::thread threadObj( (WorkerThread()) );
// Program will terminate as we have't called either join or detach with the std::thread object.
// Hence std::thread's object destructor will terminate the program
return 0;
}