Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding pthread_detach

Tags:

c

pthreads

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?

like image 895
John Reddock Avatar asked Nov 10 '12 06:11

John Reddock


1 Answers

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.

like image 169
Giuseppe Guerrini Avatar answered Sep 21 '22 11:09

Giuseppe Guerrini