尝试退出线程时线程调用了更多次

Thread called more times while trying to exit from a thread

我写了一个创建两个线程的程序,每个线程调用一个函数,该函数基本上打印然后调用 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(理想):

Hello SO

输出 2(理想):

Hello SO

Hello SO

输出 3(不可取,因为线程只调用函数两次):

Hello SO

Hello SO

Hello SO

请帮我找出输出 3 的解决方案。 注意:如果我删除 exit().

一切正常

这可能是由于 exit() 的 glibc 实现中的错误导致无法解释的输出——输出多于线程数。 当进程通过调用 exit() 退出时,它必须刷新所有流,包括 stdout,以写入缓冲区中所有未写入的输出。 所以 stdout 的缓冲区中可能有一个 "more" 而不是你想要的。

stdout 附加到终端设备时通常是行缓冲区。所以我怀疑你要么在 printf 中没有 \n 要么做了某种输出重定向(比如 pipe/rediecting 到一个文件)。

IIRC,glibc 实现者没有修复它,作为修复,您可以在 main() 开始时调用 setbuf(stdout, 0); 以禁用缓冲。您也可以调用 pthread_exit() 而不是调用 exit()。 记住 exit() 终止整个过程。此外,exit() 不是线程安全的。因此,只有当您知道不存在竞争条件时,您才能安全地调用它。要仅终止线程,请从线程函数中调用 pthread_exit() 或简单地调用 return。

我会 link 找到 glibc 错误报告。