C++11并发编程:多线程std::thread

2020-01-06 20:01:57丽君


void threadFun(int& a)
{
  cout << "this is thread fun !" << endl;
}  
int value = 2;
thread t1(threadFun, std::ref(value));

4.Move构造函数

thread(thread&& x)noexcept

调用成功原来x不再是std::thread对象


void threadFun(int& a)
{
  cout << "this is thread fun !" << endl;
} 
int value = 2;
thread t1(threadFun, std::ref(value));
thread t2(std::move(t1));
t2.join();

三:成员函数

1.get_id()

获取线程ID,返回类型std::thread::id对象。


thread t1(threadFun);
thread::id threadId = t1.get_id();
cout << "线程ID:" << threadId << endl;
//threadId转换成整形值,所需头文件<sstream>
ostringstream  oss;
oss << t1.get_id();
string strId = oss.str();
unsigned long long tid = stoull(strId);
cout << "线程ID:" << tid << endl;

2.join()

创建线程执行线程函数,调用该函数会阻塞当前线程,直到线程执行完join才返回。


thread t1(threadFun);
t1.join() //阻塞等待

3.detach()

detach调用之后,目标线程就成为了守护线程,驻留后台运行,与之关联的std::thread对象失去对目标线程的关联,无法再通过std::thread对象取得该线程的控制权。

4.swap()