Search code examples
c++multithreadingc++11

How to find out if we are running in main thread?


We can get the id of the main thread by calling std::this_thread::get_id() just at the start of the main function like this answer suggests. We can then store this id in a global variable and compare against a call of std::this_thread::get_id().

However, this forces us to change the main function. Is there a way to create a library function that does this? I was thinking about using a global variable initialized with std::this_thread::get_id() expression. Since global variables (variables with static duration) are initialized relatively early it is unlikely (but not impossible, see: deferred dynamic initialization) that threads are spawned before these variables are initialized.

I could also initialize the global variable with a helper function which enumerates all threads and picks the one with the earliest creation time (based on this answer).

I am very new to multithreading so any advice or guidance is extremely welcome.


Solution

  • There is no such thing as main thread. There is a thread which was launched first, but all threads are first-class citizens. By tinkering with linker flags, I can easily create a program where the thread executing main() would not be the the thread launched first.

    Rethink your design.