Reputation: 13303
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.
Upvotes: 9
Views: 12608
Reputation: 674
Here's a solution for Linux:
#include <stdio.h>
#include <string>
#include <thread>
#include <unistd.h>
#include <sys/syscall.h>
void check_thread() {
if (syscall(SYS_gettid) == getpid()) {
printf("Hello from main thread\n");
}
else {
printf("Hello from child thread\n");
}
}
int main() {
check_thread();
std::thread t(check_thread);
t.join();
}
Upvotes: 1
Reputation: 1209
If you are using MFC. You can check AfxGetMainWnd()
. If it return a pWnd then you have the (MFC) main thread. Disclaimer: If you have not manipulatued the m_pMainWnd
Pointer.
Upvotes: 0
Reputation: 62583
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.
Upvotes: 17
Reputation: 1025
EDIT
This is not a solid way of getting the main thread's ID considering what @ta.speot.is and @David Schwartz said.
You could make a static variable somewhere that initializes with the current thread's ID.
const std::thread::id MAIN_THREAD_ID = std::this_thread::get_id();
And then somewhere else:
if (std::this_thread::get_id() == MAIN_THREAD_ID)
{
std::cout << "main thread\n";
}
else
{
std::cout << "not main thread\n";
}
Upvotes: 10