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
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() .
In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.
if (status == std::future_status::ready) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } t. join(); // Join thread. } This is of course because the thread status is checked before the task is finished.
2.1. Basic thread management. Every C++ program has at least one thread, which is started by the C++ runtime: the thread running main() . Your program can then launch additional threads that have another function as the entry point. These threads then run concurrently with each other and with the initial thread.
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.
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