在阅读了这个答案和Robert Love的《Linux内核开发》以及
最近我编写了一个涉及几个POSIX线程的程序,并决定对此进行实验。在创建两个线程的进程中,所有线程当然都通过
下面是我创建的一个示例程序:
clone()
系统调用之后,我发现在Linux中进程和线程对于内核来说(几乎)无法区分。它们之间有一些微小的差别(在引用的SO问题中被讨论为“更多共享”或“更少共享”),但我仍然有一些问题尚未得到解答。最近我编写了一个涉及几个POSIX线程的程序,并决定对此进行实验。在创建两个线程的进程中,所有线程当然都通过
pthread_self()
返回唯一值,但是通过getpid()
返回的值却不是唯一的。下面是我创建的一个示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
void* threadMethod(void* arg)
{
int intArg = (int) *((int*) arg);
int32_t pid = getpid();
uint64_t pti = pthread_self();
printf("[Thread %d] getpid() = %d\n", intArg, pid);
printf("[Thread %d] pthread_self() = %lu\n", intArg, pti);
}
int main()
{
pthread_t threads[2];
int thread1 = 1;
if ((pthread_create(&threads[0], NULL, threadMethod, (void*) &thread1))
!= 0)
{
fprintf(stderr, "pthread_create: error\n");
exit(EXIT_FAILURE);
}
int thread2 = 2;
if ((pthread_create(&threads[1], NULL, threadMethod, (void*) &thread2))
!= 0)
{
fprintf(stderr, "pthread_create: error\n");
exit(EXIT_FAILURE);
}
int32_t pid = getpid();
uint64_t pti = pthread_self();
printf("[Process] getpid() = %d\n", pid);
printf("[Process] pthread_self() = %lu\n", pti);
if ((pthread_join(threads[0], NULL)) != 0)
{
fprintf(stderr, "Could not join thread 1\n");
exit(EXIT_FAILURE);
}
if ((pthread_join(threads[1], NULL)) != 0)
{
fprintf(stderr, "Could not join thread 2\n");
exit(EXIT_FAILURE);
}
return 0;
}
这段代码是在64位Fedora上编译的[gcc -pthread -o thread_test thread_test.c
]。由于pthread_t
类型来自<bits/pthreadtypes.h>
,使用了64位类型,因此在32位版本上编译需要进行轻微修改。
下面是输出结果:
[bean@fedora ~]$ ./thread_test
[Process] getpid() = 28549
[Process] pthread_self() = 140050170017568
[Thread 2] getpid() = 28549
[Thread 2] pthread_self() = 140050161620736
[Thread 1] getpid() = 28549
[Thread 1] pthread_self() = 140050170013440
[bean@fedora ~]$
通过在 gdb
中使用调度程序锁定,我可以保持程序及其线程活动,以便捕获 top
显示的内容。 只显示进程 的内容如下:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
28602 bean 20 0 15272 1112 820 R 0.4 0.0 0:00.63 top
2036 bean 20 0 108m 1868 1412 S 0.0 0.0 0:00.11 bash
28547 bean 20 0 231m 16m 7676 S 0.0 0.4 0:01.56 gdb
28549 bean 20 0 22688 340 248 t 0.0 0.0 0:00.26 thread_test
28561 bean 20 0 107m 1712 1356 S 0.0 0.0 0:00.07 bash
展示线程时,显示:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
28617 bean 20 0 15272 1116 820 R 47.2 0.0 0:00.08 top
2036 bean 20 0 108m 1868 1412 S 0.0 0.0 0:00.11 bash
28547 bean 20 0 231m 16m 7676 S 0.0 0.4 0:01.56 gdb
28549 bean 20 0 22688 340 248 t 0.0 0.0 0:00.26 thread_test
28552 bean 20 0 22688 340 248 t 0.0 0.0 0:00.00 thread_test
28553 bean 20 0 22688 340 248 t 0.0 0.0 0:00.00 thread_test
28561 bean 20 0 107m 1860 1432 S 0.0 0.0 0:00.08 bash
看起来很明显,程序或内核与进程相比有一种独特的定义线程的方式。每个线程根据top
都有自己的PID - 为什么呢?
clone()
只是 Linux 实现线程和fork()
的方式。重要的是,与 PID 通信将把信号传递给所有需要知道的人。如果内核为线程分配其他 ID,则这与您与进程通信的方式无关,也不影响您的业务。 - Kerrek SB