Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

id of "main" thread in c++

Is there a way in c++ to get the id of the "main" program thread?

I see that std::this_thread::get_id() gets the id of the currently executing thread but I need the id of the main, original program thread. I don't see any function to get this.

The reason is that I have some non thread safe internal functions that must only be called on the original thread of the application so to be safe I want to do :-

assert(std::this_thread::get_id() == std::main_thread::get_id());

But there of course isn't a function to do that, and I can't see any way to get that information.

like image 810
jcoder Avatar asked Nov 08 '12 11:11

jcoder


People also ask

How do I find the main thread ID?

Use GetCurrentThreadId to get the thread Id from the main thread.

What is main thread in C?

When a C# program starts up, one thread begins running immediately. This is usually called the main thread of our program. Properties: It is the thread under which other “child” threads will be created.

What is the thread ID?

Thread Id is a long positive integer that is created when the thread was created. During the entire lifecycle of a thread, the thread ID is unique and remains unchanged. It can be reused when the thread is terminated.

Does a thread have an ID?

In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.


2 Answers

You could save it while this_thread is still the original thread:

std::thread::id main_thread_id;

int main() {
    main_thread_id = std::this_thread::get_id(); // gotcha!
    /* go on */
}
like image 60
R. Martinho Fernandes Avatar answered Oct 13 '22 15:10

R. Martinho Fernandes


This topic seems to be discussed quite a few times here, like in this topic:

  • Getting a handle to the process main thread

You can find some solutions, but I'd just think the other way round... When starting the new threads, just supply the id of the main thread to them, and store that in a field in the other threads. If that is not going to change throughout the threads' life, you're good to go, you can reference the "main" thread by those handles.

like image 42
ppeterka Avatar answered Oct 13 '22 15:10

ppeterka