如何在Linux内核3.2中实现pthread? [英] How does pthread implemented in linux kernel 3.2?

查看:243
本文介绍了如何在Linux内核3.2中实现pthread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

下面的代码来自"Unix环境中的高级编程",它创建一个新线程,并打印主线程和新线程的进程ID和线程ID.

The code below comes from "Advanced Programing in Unix Environment", it creates a new thread, and prints the process id and thread id for main and new threads.

在书中说,在linux中,此代码的输出将显示两个线程具有不同的 进程ID,因为pthread使用轻量级进程来模拟线程.但是,当我在Ubuntu 12.04中运行此代码时,它具有内核3.2,并打印了相同的pid.

In the book, it said that in linux, the output of this code would show that two threads have different process ids, because pthread uses lightweight process to emulate thread. But when I ran this code in Ubuntu 12.04, it has kernel 3.2, printed the same pid.

那么,新的Linux内核会改变pthread的内部实现吗?

so, does the new linux kernel change the internal implementation of pthread?

#include "apue.h"
#include <pthread.h>

pthread_t ntid;

void printids(const char *s) {
  pid_t     pid;
  pthread_t tid;
  pid = getpid();
  tid = pthread_self();
  printf("%s pid %u tid %u (0x%x)\n",
         s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}

void *thread_fn(void* arg) {
  printids("new thread: ");
  return (void *)0;
}

int main(void) {
  int err;
  err = pthread_create(&ntid, NULL, thread_fn, NULL);
  if (err != 0)
    err_quit("can't create thread: %s\n", strerror(err));
  printids("main thread: ");
  sleep(1);
  return 0;
}

推荐答案

在Linux上,pthread使用带有特殊标志CLONE_THREADclone系统调用.

On Linux pthread uses the clone syscall with a special flag CLONE_THREAD.

请参阅clone syscall的文档.

See the documentation of clone syscall.

CLONE_THREAD(从Linux 2.4.0-test8开始)

CLONE_THREAD (since Linux 2.4.0-test8)

如果设置了CLONE_THREAD,则将子级与调用进程放在同一线程组中.为了使CLONE_THREAD讨论的其余部分更具可读性,术语线程"用于指代线程组中的进程.

If CLONE_THREAD is set, the child is placed in the same thread group as the calling process. To make the remainder of the discussion of CLONE_THREAD more readable, the term "thread" is used to refer to the processes within a thread group.

线程组是Linux 2.4中新增的一项功能,用于支持共享单个PID 的一组线程的POSIX线程概念.在内部,此共享PID是线程组的所谓线程组标识符(TGID).从Linux 2.4开始,对getpid(2)的调用将返回调用者的TGID.

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.

实际上,Linux可以更改其线程实现,因为 POSIX.1要求线程共享同一进程ID.

And in fact, Linux do change its thread implementation, since POSIX.1 requires threads share a same process ID.

   In the obsolete LinuxThreads implementation, each of the threads in a process
   has a different process ID.  This is in violation of the POSIX threads
   specification, and is the source of many other nonconformances to the
   standard; see pthreads(7).

这篇关于如何在Linux内核3.2中实现pthread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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