c++ - 检查当前线程是否为主线程

标签 c++ c linux multithreading pthreads

如何检查当前线程是否是 linux 上的主线程?看起来 gettid() 只返回一个 pid,但似乎 linux 不保证 main() 的线程总是有一个常量和统一的 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++ - 检查当前线程是否为主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530218/

相关文章:

c - 3.3 书 k&r 中的上下文问题

linux - U-boot 在不同的内核上加载两个图像

linux - 加快文件从一台机器传输到另一台机器

c++ - 当我将指向对象的指针设置为 NULL 时,为什么会出现段错误?

c++ - 对 Microsoft C++ 产品和术语感到困惑

c++ - 将变量从一个函数传递给另一个麻烦(C++)

c++ - 获取常见文件类型的图标

c - 在控制台上显示

c - 什么是 "Signal 15 received"

linux - 我可以从 VS2005 远程调试 linux 机器吗?