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

c – 检查当前线程是否为主线程,第1张

概述我如何检查当前线程是否是 linux上的主线程?看起来gettid()只返回一个pid,但似乎linux不保证main()的线程总是有一个const和统一的pid. 原因是我有一个自动并行化,我想确保pthread_create()没有被一个已经在由pthread_create()创建的线程上运行的函数中调用. 对于 Linux: 如果getpid()返回与gettid()相同的结果,那么它是主线 我如何检查当前线程是否是 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).

总结

以上是内存溢出为你收集整理的c – 检查当前线程是否为主线程全部内容,希望文章能够帮你解决c – 检查当前线程是否为主线程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1249017.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存