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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With