加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 检查当前线程是否为主线程

发布时间:2020-12-16 05:39:47 所属栏目:百科 来源:网络整理
导读:我如何检查当前线程是否是 linux上的主线程?看起来gettid()只返回一个pid,但似乎linux不保证main()的线程总是有一个const和统一的pid. 原因是我有一个自动并行化,我想确保pthread_create()没有被一个已经在由pthread_create()创建的线程上运行的函数中调用.
我如何检查当前线程是否是 linux上的主线程?看起来gettid()只返回一个pid,但似乎linux不保证main()的线程总是有一个const和统一的pid.

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

解决方法

对于 Linux:

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

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

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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读