在阅读了这个答案和Robert Love的“LinuxKernelDevelopment”之后,随后在clone()系统调用中,我发现Linux中的进程和线程(几乎)与内核没有区别。它们之间有一些调整(在引用的SO问题中被讨论为“更多共享”或“更少共享”),但是我仍然有一些问题需要解答。
我最近开发了一个包含几个POSIX线程的程序,并决定在此前提下进行试验。在创建两个线程的进程中,所有线程当然都会获得的唯一值pthread_self(),
但 不是getpid()。
我创建的示例程序如下:
#include
#include
#include
#include
#include
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;
}
(这被编译[ gcc -pthread -o thread_test
thread_test.c]在64位的Fedora;由于用于64位类型pthread_t从来源,代码将需要小的变化来编译在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
似乎很清楚,程序或内核与进程相比,具有一种定义线程的独特方法。每个线程根据其都有自己的PID- top为什么?