thread 类
C++11的支持的thread线程库对原生的pthread库进行了封装,原本pthread_create函数只能传递一个参数,而新的thread类更为灵活。
部分构造函数如下,其中复制构造函数都已处于delete状态,不再使用:
thread() noexcept = default;
thread(thread&& __t) noexcept // 移动构造函数
template<typename _Callable, typename... _Args> // 这里还用到了C++11的可变模板参数
explicit thread(_Callable&& __f, _Args&&... __args)
thread(_Callable&& __f, _Args&&... __args)
,可以传入线程执行函数的同时直接传入可变的参数,比起原生pthread库实在方便很多。
thread 类主要方法
get_id()
——获取线程ID,返回类型std::thread::id对象。参考get_idjoinable()
——判断线程是否可以加入等待。参考joinablejoin()
——等该线程执行完成后才返回。参考joindetach()
——将本线程从调用线程中分离出来,允许本线程独立执行。(当主进程结束时,不管子进程是否detach()都会被杀死)。参考detach
简单创建线程的代码示例
由于用到pthread库,因此编译时要加-lpthread
选项。
#include <iostream>
#include <thread>
using namespace std;
void work1()
{
cout << "This is work1\n";
}
void work2(int a, int b)
{
cout << "work2 a + b = " << a + b << endl;
}
int main()
{
thread t1(work1);
cout << "thread id " << t1.get_id() << " running...\n";
if(t1.joinable())
t1.join();
thread t2(work2, 1, 2); // 可直接传右值参数
cout << "thread id " << t2.get_id() << " running...\n";
if(t2.joinable())
t2.join();
}
输出:
thread id This is work1 # 此处由于线程交替执行打印出现混乱
139923688707840 running...
thread id 139923688707840 running...
work2 a + b = 3