What is the difference between below methods for getting thread ID in C++?

How to get thread ID in C++?
(reference code: http://www.cplusplus.com/reference/thread/thread/get_id/)

1. I try to get the thread ID of th by two methods as given in comments: (1) and (2), but the (2) always give the value 0. Why the results between (1) and (2) are different?
2. For comment (3), when I remove this line “th.join();” and compile using visual studio , there will be a debug error causing abort function. Why the debug error happens?

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
// thread::get_id / this_thread::get_id

#include <iostream> // std::cout

#include <thread> // std::thread, std::thread::id, std::this_thread::get_id

#include <chrono> // std::chrono::seconds

std::thread::id main_thread_id = std::this_thread::get_id();

void is_main_thread() {

if (main_thread_id == std::this_thread::get_id())

std::cout << "This is the main thread.\n";

else

std::cout << "This is not the main thread.\n";

std::cout << "std::this_thread::get_id() is:" << std::this_thread::get_id() << "\n";

}

int main()

{

std::cout << "main_thread_id is:" << main_thread_id << "\n";

is_main_thread();

std::thread th(is_main_thread); // (1) create a thread named th and execute function is_main_thread(); print thread ID of th;

th.join(); // (3)

std::cout << "th's thread_id is:" << th.get_id() << "\n"; // (2) print thread id of th

}
Last edited on
> Why the results between (1) and (2) are different?

After line 35 th.join(), there is no thread of execution associated with the object th.

On line 37, th.get_id() returns a default constructed thread id
(a value that indicates that there is no thread of execution associated with this thread object).


> when I remove this line “th.join();” ... there will be a debug error causing abort function.
> Why the debug error happens?

At the end of main(), when the destructor of the thread object th is invoked, it has an associated thread of execution - join() or detach() has not been called. In this situation, the destructor of the thread calls std::terminate(). The default handler for std::terminate() calls std::abort().
Topic archived. No new replies allowed.