了解pthread_detach [英] Understanding pthread_detach

查看:214
本文介绍了了解pthread_detach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的打印

 在main()
你好,世界
你好,世界

为什么这打印的Hello World两次?如果我使用在pthread_join()所需的输出时由pceeded在main()。(只有一个世界您好$ P $

 的#include< pthreads.h中>无效* thread_func(无效* ARG);INT主(INT ARGC,字符** argv的)
{
    int类型;
    void *的资源;
    T1的pthread_t;    S =在pthread_create(安培; T1,NULL,thread_func,的Hello World \\ n);    如果(S!= 0)
        的printf(ERR \\ n);    的printf(在main()\\ n);    S = pthread_detach(T1);    如果(S!= 0)
        的printf(ERR \\ n);    返回0;
}无效* thread_func(无效* ARG)
{
    字符* S =(字符*)ARG;
    的printf(%S,S);
    了pthread_exit(0);
}

我明白pthread_detach告诉库一旦线程终止释放所有被pthread的利用资源......因为我在thread_func年底终止,一切都应该没关系吧?

我是什么在这里失踪?


解决方案

在我看来,你所使用的标准库的非线程安全版本(打印,fflush ...)。我已经看到这种类型的旧的Unix类的实时系统(显然)非逻辑的行为。有两个不同版本的std库,一个为单线程模式,一个用于多线程。当然,默认是单线程...
一般情况下,访问文件指针和类似的东西应该与互斥体被序列化。在程序中有两个螺纹端子,每个可能希望隐调用fflush,但由于基础缓冲区并不意味着被同时访问,可能发生的是这两个刷新写入相同的数据到输出的文件描述符。

The following prints

In Main()
Hello World
Hello World

Why does this print Hello World twice? If I use pthread_join() the desired output occurs (only one Hello World preceeded by a 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);
}

I understand pthread_detach tells the library to release all of the resources utilized by the pthread once the thread is terminated... and since I terminate it at the end of thread_func, everything should be okay right?

What am I missing here?

解决方案

In my opinion you are using a non-thread-safe version of the standard library (prints, fflush...). I have already seen this kind of (apparently) non-logical behavior on a old unix-like real time system. There were two different versions of std library, one for single-threaded mode and one for multithreaded. Of course, the default was single threaded... In general, accesses to file pointers and similar things should be serialized with mutexes. In your program there are two thread terminations, each may want to call implicitly an fflush, but since the underlying buffers are not meant to be accessed concurrently, it may happen that both flushes write the same data to the output file descriptor.

这篇关于了解pthread_detach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆