(6)std::thread

#include<thread> 头文件
std::thread为C++11的线程类,使用方法和boost接口一样,非常方便。
C++11的std::thread解决了boost::thread中构成参数限制的问题。
获得主线程ID:
std::this_thread::get_id()

获得线程ID:
std::thread::get_id();

获得当前多少个线程:
std::thread::hardware_concurrency()

线程睡眠
this_thread::sleep_for(chrono::milliseconds(10));

主线程等待直到该子线程执行结束
thread::join()

线程对象分离,线程独立地执行
thread::detach()

判断线程是否可以加入等待
thread::joinable()

线程交换
thread::swap()

获取线程句柄
thread::native_handle()

检测硬件并发特性
thread::hardware_concurrency()
构造:
1. 接收一个函数指针和参数列表
std::thread t1(func, 1);

2. 接收lambda表达式
std::thread t2([]() {std::cout<< std::this_thread::get_id() << std::endl;}); 
 
3. 函数对象, (函数对象必须重载了 operator()):
std::thread t3(new STNode());
或者
std::thread t3(&STNode::run, &node);  //成员函数 + 对象地址

4. 移动构造函数 (线程所有权转移)
std::thread t2(std::move(t1));
posted @ 2018-12-08 14:32  osbreak  阅读(237)  评论(0)    收藏  举报