检查当前螺纹是否是主螺纹 [英] Check if current thread is main thread

查看:220
本文介绍了检查当前螺纹是否是主螺纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查当前线程是否是linux上的主线程?看起来像gettid()只返回一个pid,但似乎linux不保证线程与main()总是有一个const和统一的pid。



这样做的原因是我有一个自动并行化,我想确保pthread_create()没有在一个已经在线程上运行的函数中被调用

$ p

对于Linux:


如果 getpid()返回与 gettid()相同的结果,它是主线程。

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

man gettid


gettid()返回调用者的线程ID(TID)。在单线程进程中,线程ID等于进程ID(PID,由 getpid(2)返回)。在多线程进程中,所有线程都具有相同的PID,但每个
都有唯一的TID。


man clone


在Linux 2.4中支持
POSIX线程的一组线程的概念,共享一个
PID。在内部,这个共享PID是线程组的所谓线程
组标识符(TGID)。由于Linux
2.4,调用 getpid(2)返回调用者的TGID。



由它们的
(系统范围)唯一线程ID(TID)区分。新线程的TID是
,作为函数结果返回给
clone()的调用者,线程可以使用 gettid(2)



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

解决方案

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

这篇关于检查当前螺纹是否是主螺纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆