1.get_id()
获取线程ID,返回类型std::thread::id对象。
2.join()
创建线程执行线程函数,调用该函数会阻塞当前线程,直到线程执行完join才返回。
3.detach()
detach调用之后,目标线程就成为了守护线程,驻留后台运行,与之关联的std::thread对象失去对目标线程的关联,无法再通过std::thread对象取得该线程的控制权
4.swap()
交换两个线程对象
thread t1(threadFun1);
thread t2(threadFun2);
cout << "线程1的ID:" << t1.get_id() << endl;
cout << "线程2的ID:" << t2.get_id() << endl;
t1.swap(t2);
cout << "线程1的ID:" << t1.get_id() << endl;
cout << "线程2的ID:" << t2.get_id() << endl;
5.hardware_concurrency()
获得逻辑处理器储量,返回值为int型
int coreNum = thread::hardware_concurrency();
#include <iostream>
#include <sstream>
#include <thread>
void threadFun()
{
std::cout << "threadFun is called!"<<std::endl;
}
int main()
{
std::thread t1(threadFun);
std::thread::id threadId = t1.get_id();
std::cout << "线程ID:" << threadId << std::endl;
//threadId转换成整形值,所需头文件<sstream>
std::ostringstream oss;
oss << t1.get_id();
std::string strId = oss.str();
unsigned long long tid = stoull(strId);
std::cout << "线程ID:" << tid << std::endl;
t1.join();
//t1.detach();
int coreNum = std::thread::hardware_concurrency();
std::cout << "coreNum:"<<coreNum;
return 0;
}
Output:
线程ID:140100790527744
threadFun is called!
线程ID:140100790527744
coreNum:4