c - 了解 pthread_detach

标签 c pthreads

打印如下

In Main()
Hello World
Hello World

为什么要打印两次 Hello World?如果我使用 pthread_join() 会出现所需的输出(只有一个 Hello World 前面有一个 In Main()。

#include <pthread.h>

void *thread_func(void *arg);

int main(int argc, char **argv)
{
    int s;
    void *res;
    pthread_t t1;

    s = pthread_create(&t1, NULL, thread_func, "Hello World\n");

    if (s != 0)
        printf("Err\n");

    printf("In Main()\n");

    s = pthread_detach(t1);

    if (s != 0)
        printf("Err\n");

    return 0;
}

void *thread_func(void *arg)
{
    char *s = (char *)arg;
    printf("%s", s);
    pthread_exit(0);
}

我理解 pthread_detach 告诉库在线程终止后释放 pthread 使用的所有资源...并且由于我在 thread_func 结束时终止它,所以一切都应该没问题吧?

我在这里错过了什么?

最佳答案

在我看来,您使用的是标准库的非线程安全版本(prints、fflush...)。我已经在旧的类 unix 实时系统上看到过这种(显然)非逻辑行为。有两种不同版本的 std 库,一种用于单线程模式,一种用于多线程。当然,默认是单线程的...... 通常,对文件指针和类似事物的访问应该使用互斥锁进行序列化。在您的程序中有两个线程终止,每个终止都可能想隐式调用 fflush,但由于底层缓冲区不打算同时访问,因此可能会发生两个刷新将相同数据写入输出文件描述符的情况。

关于c - 了解 pthread_detach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13319793/

相关文章:

c - 为什么不能在 pthread 中访问 Cocoa 控件?

C 编程,从重复的代码中创建循环

c - Linux 的 dos.h?

c - 多线程程序中的输出

c - 不确定我是否需要互斥锁

c++ - Linux 内核 2.4.20 和 2.4.36 中的 pthread_create 差异

为已经退出的线程调用 pthread_detach?

c - 为什么在 C 中 const 对象不是编译时常量表达式?

c - 如何用256位AVX vector 对两个复数 double 平方?

c - Win32 WriteFile 返回 0 字节作为写入的字节数。 lpBuffer 包含 4455 字节