格式:函數 + 頭文件 + 用例 + 解釋說明
函數: 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(); }
輸出結果: