如何取得 C++11 thread id

本篇介紹如何取得 C++11 的 std::thread::id,有時候在 C++ 多執行緒的情況下,我們會需要印出 thread id 以方便判斷各自是哪個執行緒,以下範例就是簡單的取得 std::thread::id 的範例。

範例1. 取得 std::thread::id

std-thread-get-thread-id1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// g++ std-thread-get-thread-id1.cpp -o a.out -std=c++11 -pthread
#include <iostream>
#include <thread>
#include <chrono>
#include <assert.h>

using namespace std;

void foo() {
std::thread::id tid = std::this_thread::get_id();
cout << "foo thread id : " << tid << "\n";
}

int main() {
std::thread t1(foo);

std::thread::id tid = t1.get_id();
std::thread::id mainTid = std::this_thread::get_id();

if (t1.joinable())
t1.join();

cout << "t1 tid: " << tid << endl;
cout << "main tid: " << mainTid << endl;

return 0;
}

輸出

1
2
3
foo thread id : 140532863575808
t1 tid: 140532863575808
main tid: 140532880869184

範例2. join 與 detach 的 std::thread::id

std-thread-get-thread-id2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// g++ std-thread-get-thread-id2.cpp -o a.out -std=c++11 -pthread
#include <iostream>
#include <thread>
#include <chrono>
#include <assert.h>

using namespace std;

void foo() {
cout << "foo start\n";
std::thread::id tid = std::this_thread::get_id();
cout << "foo thread id : " << tid << "\n";
cout << "foo end\n";
}

int main() {
std::thread t1(foo);

std::thread::id tid = t1.get_id();

if (t1.joinable())
t1.join();

cout << "Thread from Main : " << tid << endl;

std::thread t2(foo);

t2.detach();

std::thread::id tid2 = t2.get_id();

assert(tid2 == std::thread::id());

cout << "sleep 2s\n";
std::this_thread::sleep_for(std::chrono::seconds(2));

cout << "Thread from Main : " << tid2 << endl;

return 0;
}

輸出

1
2
3
4
5
6
7
8
9
foo start
foo thread id : 140447362262784
foo end
Thread from Main : 140447362262784
sleep 2s
foo start
foo thread id : 140447362262784
foo end
Thread from Main : thread::id of a non-executing thread

參考
How to get a Thread ID ?
https://thispointer.com/c11-how-to-get-a-thread-id/

相關文章
C/C++ 新手入門教學懶人包
std::thread 用法與範例