C++11中多线程thread详解

参考: http://en.cppreference.com/w/cpp/thread/thread

joinable

Check if joinable Returns whether the thread object is joinable.
返回线程对象是否是joinable的。

A thread object is not joinable in any of these cases:
下列任一情况都是非joinable

if it was default-constructed.
默认构造器构造的。

if it has been moved from (either constructing another thread object, or assigning to it).
通过移动构造获得的。

if either of its members join or detach has been called.
调用了join或者detach方法的。

我们来看源码,实际上该函数就是判断当前线程的id是否为0

源码如下:

1
2
3
4
5
6
#define _Thr_is_null(thr) (thr._Id == 0)

bool joinable() const _NOEXCEPT
{ // return true if this thread can be joined
return (!_Thr_is_null(_Thr));
}

join

等待子线程执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源

detach

如果不想等待子线程,可以在主线程里面执行detach()将子线程从主线程里分离,子线程执行完成后会自己释放掉资源。分离后的线程,主线程将对它没有控制权了。

版权所有,如有侵权请联系我