我编写了一个创建两个线程的程序,每个线程调用一个函数,该函数基本上打印然后调用 exit()
。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
void *myfunc(void* myvar)
{
printf("Hello SO\n");
exit(1);
return NULL;
}
int main()
{
pthread_t thread1 , thread2;
char *msg1 = "First Thread";
char *msg2 = "Second Thread";
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, myfunc, (void*)msg1);
ret2 = pthread_create(&thread2, NULL, myfunc, (void*)msg2);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
return 0;
}
我得到以下几组输出:
输出 1(理想):
你好
输出 2(理想):
你好
你好
输出 3(不可取,因为线程只调用函数两次):
你好
你好
你好
请帮我找出输出 3 的解决方案。
注意:如果我删除 exit()
,一切正常。
最佳答案
这可能是由于 exit()
的 glibc 实现中的一个错误,它是无法解释的输出——比线程数更多的输出。
当进程通过调用 exit()
退出时,它必须刷新所有流,包括 stdout,以写入缓冲区中所有未写入的输出。
因此,stdout
的缓冲区中可能存在比您想要的“更多”的内容。
stdout
在连接到终端设备时通常是行缓冲区。所以我怀疑您在 printf 中没有 \n
或进行某种输出重定向(例如通过管道/重定向到文件)。
IIRC,glibc 实现者没有修复它,作为修复,您可以在 main() 的开头调用 setbuf(stdout, 0);
以禁用缓冲。您也可以调用 pthread_exit()
而不是调用 exit()
。
请记住 exit()
会终止整个过程。此外,exit()
不是线程安全的。因此,只有当您知道不存在竞争条件时,您才能安全地调用它。要仅终止线程,请调用 pthread_exit()
或简单地从线程函数返回。
我会在找到 glibc 错误报告时链接它。
关于c - 尝试退出线程时线程调用了更多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33999081/