C++11 Multithreading – Part 2: Joining and Detaching Threads
Joining Threads with std::thread::join()
一个线程启动后,另一个线程可以等待该线程完成。这个特别的需求可以用join来实现:
1 | std::thread th(funcPtr); |
Detaching Threads using std::thread::detach()
被分离的线程也叫守护(daemon)/后台(background)线程,这个需求可以调用std::function来完成:
1 | std::thread th(funcPtr); |
Be careful with calling detach() and join() on Thread Handles
Case 1: Never call join() or detach() on std::thread object with no associated executing thread std::thread threadObj( (WorkerThread()) ); threadObj.join(); threadObj.join(); // It will cause Program to Terminate
比如在一个没有相关线程的线程上执行join或者detach都会导致程序终止:
1 | std::thread threadObj( (WorkerThread()) ); |
为了避免这个问题,每次调用join()或者detach()之前都应该检查线程状态:
1 | std::thread threadObj( (WorkerThread()) ); |
Case 2 : Never forget to call either join or detach on a std::thread object with associated executing thread
如果一个线程还有相关联的在执行的线程,但却没有对此执行join()或者detach(),那么在destructor中会终止该程序。因为destructor会检查线程是否joinable。
1 |
|