Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread detect main thread

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

like image 548
moka Avatar asked Jul 13 '12 11:07

moka


People also ask

How do you find the main thread in C++?

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() .

How do I find my main thread 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.

How do you check if a thread is alive in C++?

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.

What is main thread in C++?

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.


1 Answers

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.

like image 77
Nawaz Avatar answered Oct 14 '22 08:10

Nawaz