Reputation: 4491
is thre any relieable way in c++11 to detect if the current thread is the main thread? Or would I have to manually save the main threads thread id with std::this_thread::get_id()
and then have a routine like this:
bool isMainThread()
{
return theMainThreadIdISavedOnProgramStart == std::this_thread::get_id();
}
Is there a common way to do this? Would the above solution work?
Thanks
Upvotes: 9
Views: 4060
Reputation: 361512
What do you mean by main thread? If you mean, the thread which executes main()
, then there is no way you can know if a thread is a main thread or not. You've to save its ID and later on you can use the saved ID to know if a current thread is a main thread or not, by comparing its ID with the saved ID (as you guessed in your question).
To explain it a bit more, threads do not have hierarchy, there is no parent thread, no child thread even if one thread creates the other threads. The OS doesn't remember which threads created by which thread. Therefore, all threads are same to the OS, and to your program. So you cannot infer a main
thread, by detecting if the current thread is the parent of all other threads in your application.
Upvotes: 12