Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if current thread is main thread

How can i check if the current thread is the main thread on linux? It looks like gettid() only returns an pid but it seems that linux does not guarantee the thread with main() always has a const and uniform pid.

The reason for this is that I have an automatic parallelization going on and I want to make sure pthread_create() is not called in a function that is already running on a thread that's created by pthread_create().

like image 816
user2958862 Avatar asked Dec 11 '13 21:12

user2958862


1 Answers

For Linux:

If getpid() returns the same result as gettid() it's the main thread.

int i_am_the_main_thread(void)
{
  return getpid() == gettid();
}

From man gettid:

gettid() returns the caller's thread ID (TID). In a single-threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one has a unique TID.

From man clone:

Thread groups were a feature added in Linux 2.4 to support the POSIX threads notion of a set of threads that share a single PID. Internally, this shared PID is the so-called thread group identifier (TGID) for the thread group. Since Linux 2.4, calls to getpid(2) return the TGID of the caller.

The threads within a group can be distinguished by their (system-wide) unique thread IDs (TID). A new thread's TID is available as the function result returned to the caller of clone(), and a thread can obtain its own TID using gettid(2).

like image 107
alk Avatar answered Oct 16 '22 16:10

alk