GNU/Linux线程实现

ars*_*ars 5 c linux pthreads

最近,我在"高级Linux编程"一书(http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf,第4.5章)中读到,在GNU/Linux上POSIX线程实现为进程和某种"管理器线程",它做一些控制工作.

当我从本书中运行以下示例时:

#include <stdio.h>
#include <pthread.h>

void* thread_func(void *arg)
{
  fprintf(stderr, "thread: %d\n", (int)getpid());
  while(1);
  return NULL;
}

int main()
{
  fprintf(stderr, "main: %d\n", (int)getpid());

  pthread_t thread;
  pthread_create(&thread, NULL, thread_func, NULL);

  while(1);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我已经收到了主线程和子线程的相同PID,而书中说它可以是不同的,并且还有另一个PID,它对应于所谓的"管理器线程".我试图找到关于这个"经理线程"的一些信息,但事实证明这很困难.

UPD.我对我的节目的行为毫不怀疑,但是对于行为有一些混淆,在书中解释 - 特别是在哪种情况下它可能是真的?

AAD*_*ing 1

只需阅读书中的相关内容和您分享的示例,很明显它与具体实现相关POSIX threads on GNU/Linux

In GNU/Linux, threads are implemented as processes. 
Run Code Online (Sandbox Code Playgroud)

因此,每当你打电话时pthread_create创建新线程时,Linux 都会创建一个运行该线程的新进程。

因此,在示例代码中,当您执行pthread_create(&thread, NULL, thread_func, NULL);实现时,会创建一个新进程来运行这个新创建的线程。这个进程将有一个不同的PID(这就是getpid()调用显示的内容)。

因此,现在您已经有了 2 个进程,一个是运行程序时启动的主进程,另一个是系统创建的用于支持线程执行的新进程。

相同的实现还创建另一个进程(在其实现的内部),称为管理器线程。这是在您调用时创建的pthread_create