pthread_join 函数的文档说:
无法加入可加入的线程(即, 未分离),产生“僵尸线程”。
据我理解这个语句,线程终止后,它仍然是僵尸,直到我们调用 pthred_join。然而,我写了一个程序,结果发现完成的joinable线程在返回后就完全终止了。那么我们如何获取 pthread_join 中的线程退出代码呢?退出代码存储在哪里?
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
void *mythread(void *arg)
{
printf("mythread [%d %d %d]: Hello from mythread!\n", getpid(), getppid(), gettid());
int *result = malloc(sizeof(int));
*result = 42;
return result;
}
int main() {
pthread_t tid;
int err;
printf("main [%d %d %d]: Hello from main!\n", getpid(), getppid(), gettid());
err = pthread_create(&tid, NULL, mythread, NULL);
if (err) {
printf("main: pthread_create() failed: %s\n", strerror(err));
return -1;
}
sleep(1000);
void *thread_result;
if (pthread_join(tid, &thread_result) != 0) {
perror("Thread join failed");
return 1;
}
printf("Thread returned: %d\n", *((int *)thread_result));
return 0;
}
可以看到进程表中只有主线程。
尚未加入的可加入线程的线程退出代码存储在僵尸线程中。这或多或少就是僵尸线程:存储线程退出代码的数据片段。
在 Linux 下,僵尸线程不是进程(即在进程表中没有条目),因此
ps
不会显示它。 pthread_exit
调用 exit
(系统调用,而不是同名的 C 库函数),以便与该线程对应的进程真正终止。进程表中没有它的踪迹。然而,某处仍然挂着僵尸线程。