您的位置:首页 > 运维架构 > Linux

GNU/Linux 线程实现

2010-08-14 22:55 351 查看
4.5 GNU/Linux 线程实现
GNU/Linux平台上的POSIX线程实现与其它许多类UNIX操作系统上的实现有所不同:在GNU/Linux系统中,线程就是用进程实现的。每当你用pthread_create创建一个新线程的时候,Linux创建一个新进程运行这个线程的代码。不过,这个进程与一般由fork创建的进程有所不同;具体来说,新进程与父进程共享地址空间和资源,而不是分别获得一份拷贝。
列表4.15中的程序thread-pid演示了这一点。这个程序首先创建一个线程,随后两个线程都调用getpid并打印各自的进程号,最后分别无限循环。
代码列表 4.15 (thread-pid) 打印线程的进程号
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_function (void* arg)
{
    fprintf (stderr, "child thread pid is %d/n", (int) getpid ());
   /* 无限循环 */
   while (1);
   return NULL;
}
int main ()
{
   pthread_t thread;
   fprintf (stderr, "main thread pid is %d/n", (int) getpid ());
   pthread_create (&thread, NULL, &thread_function, NULL);
   /* 无限循环 */
   while (1);
  return 0;
}
在后台运行这个程序,然后调用ps x显示运行中的进程。别忘了随后结束pthread_pid程序——它浪费无数CPU时间却什么也不做。这是一个可能的输出:
% cc thread-pid.c -o thread-pid -lpthread
% ./thread-pid &
[1] 14608
main thread pid is 14608
child thread pid is 14610

 

% ps x
PID TTY STAT TIME COMMAND
14042 pts/9 S 0:00 bash
14608 pts/9 R 0:01 ./thread-pid
14609 pts/9 S 0:00 ./thread-pid
14610 pts/9 R 0:01 ./thread-pid
14611 pts/9 R 0:00 ps x
% kill 14608
[1]+ Terminated ./thread-pid
Shell 程序的进程控制提示
以 [1] 开头的行是由 shell 程序输出的。当你在后台运行一个程序,shell 会分配一个任务控制代码给这个程序——在这里是 1——并打印这个程序的进程号。如果后台程序终止了,shell 会在你下次执行命令后通知你。
注意这里共有三个进程运行着thread-pid程序。第一个,进程号是14608的,运行的是程序的主函数;第三个,进程号是14610的,是我们创建来执行thread_function的线程。
那么第二个,进程号是14609的线程呢?它是“管理线程”,属于GNU/Linux线程内部实现细节。管理线程会在一个程序第一次调用pthread_create的时候自动创建。

 

问题:为什么我在ubuntu下运行时,两个线程的PID是相同的呢??

# ./thread_pid
main thread pid is 25175
child thread pid is 25175

 

 

#ps x

25219 pts/3    Rl+    0:10 ./thread_pid
25222 pts/2    Rs     0:00 bash
25232 pts/2    R+     0:00 ps x

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息