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.
Use GetCurrentThreadId to get the thread Id from the main thread.
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.
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.
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.
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 */
}
This topic seems to be discussed quite a few times here, like in this topic:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With