Std :: thread detect main thread

is there any available way in C ++ 11 to determine if the current thread is the main thread? Or I need to manually save the main thread id using std::this_thread::get_id() , and then execute the following procedure:

 bool isMainThread() { return theMainThreadIdISavedOnProgramStart == std::this_thread::get_id(); } 

Is there a general way to do this? Will the above solution work?

thanks

+7
source share
1 answer

What do you mean by the main theme? If you mean the thread that executes main() , then you cannot find out if the thread is the main thread or not. You must save its identifier, and later you can use the saved identifier to find out if the current stream is the main stream or not by comparing its identifier with the saved identifier (as you guessed in your question).

To explain this a bit, threads have no hierarchy, no parent thread, not a single child thread, even if one thread creates other threads. The OS does not remember which threads were created using the thread. Thus, all threads are the same for the OS and your program. Thus, you cannot output the main thread by indicating whether the current thread is the parent of all other threads in your application.

+8
source

All Articles