C++11多线程
class thread
上图是thread类的成员变量与成员函数。
1、创建一个线程(构造函数)
thread threadname(entrance,**args);
thread是一个类,它的构造函数也比较简单,只需要传入一个入口函数的指针以及入口函数对应的参数。
另一种创建方法(移动赋值构造,“operator=”)
thread threadname = thread(entrance, **args);
2、外部获取线程pid。
从上图可以看到,thread类自带了一个获取线程id(注意不是pid)的成员函数,我们只需要在外部调用就可以了。
(thread::id) tid = threadname.get_id();
不过,这种获取方式只能在外部获取,或者说只能用在定义了threadname的函数中调用,那么如果我希望在执行函数(entrance)中访问当前线程的线程id该如何做呢?
可以这样做:
(thread::id) tid = std::this_thread::get_id()
this_thread是本地类,包含静态成员函数get_id()。可返回本地线程的线程id.
3、joinable、join、detach
这三个函数负责处理线程的销毁工作,join和detach的主要区别在于,join阻塞主进程执行,直到所等待的线程结束。而detach相反,它不会阻塞主进程,任由线程自由终止(detach的释义为“分支,分离”),这种情况下可配合信号一起使用。
4、hardware_concurrency【static】
"""
Returns the number of hardware thread contexts.
The interpretation of this value is system- and implementation- specific, and may not be exact, but just an approximation.
Note that this does not need to match the actual number of processors or cores available in