C++多线程库的常用函数 std::this_thread::get_id()
格式:函数 + 头文件 + 用例 + 解释说明
函数: std::this_thread::get_id() 头文件: <thread> 用例: std::thread::id master_thread = std::this_thread::get_id();
另一种获取线程标识符 id 的办法:
线程标识类型为std::thread::id
可以通过调用std::thread对象的成员函数get_id()来直接获取。
如果std::thread对象没有与任何执行线程相关联,get_id()将返回std::thread::type默认构造值,这个值表示“无线程”。
练习代码:
#include <QCoreApplication> #include <thread> #include <iostream> struct run{ run(short num):m_num(num){} void operator()(){ std::cout<<"run num is "<<m_num<<std::endl; } private: short m_num; }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); std::thread::id id = std::this_thread::get_id(); std::cout<<"this thread id is "<<id<<std::endl; std::thread t(run(100)); std::cout<<"thread t id is "<<t.get_id()<<std::endl; t.join(); return a.exec(); }
输出结果: