This can be done, depending on the platform on which you are located, but absolutely not in a portable and general form ...
Mac OS X seems to be the only one with a direct and documented approach according to their pthread.h file:
int pthread_main_np(void);
I also found that FreeBSD has a pthread_np.h header that defines pthread_main_np (), so this should work with FreeBSD (at least 8.1), and OpenBSD (at least 4.8) has pthread_main_np () defined in pthread.h too, Please note that _np clearly stands for intolerance!
Otherwise, the only more βgeneral" approach that comes to mind is to compare the PID of the process with the TID of the current thread, if they match, this thread is the main one. This does not necessarily work on all platforms, it depends on whether you really can get a TID at all (you cannot use OpenBSD, for example), and if you do, if it has anything to do with PID at all or if the streaming subsystem has its own account, which is not necessarily related.
I also found that some platforms return constant values ββas TIDs for the main thread, so you can just check them out.
A brief overview of the platforms I tested:
- Linux: maybe here , syscall (SYS_gettid) == getpid () is what you want
- FreeBSD: impossible here, thr_self () seems random and not related to getpid ()
- OpenBSD: impossible here, no way to get TID
- NetBSD: maybe here , _lwp_self () always returns 1 for the main thread
- Solaris: here , pthread_self () always returns 1 for the main thread
So basically you should be able to do this directly on Mac OS X, FreeBSD, and OpenBSD.
You can use the TID == PID approach on Linux.
You can use the TID == 1 approach on NetBSD and Solaris.
Hope this helps, have a good day!
llongi Feb 01 2018-11-11T00: 00Z
source share