I'm learning pthreads. I found that the output of below code might be weird if I repeatedly run the program. I write in such a manner that thread1 "wait" for thread2, and main thread "wait" for thread1. This manner is not correct since when thead1 gets to run, thread 2 may not be available, but I still want to know why the printf in thread2 could be duplicated. Thanks!
#include <stdio.h>
#include <pthread.h>
#include <string.h>
pthread_t thread1;
pthread_t thread2;
void* thread1_entry(void* input)
{
int ret;
/* This may return error when thread2 has not been created yet*/
ret = pthread_join(thread2, NULL);
printf("hello from 1-%d-%s\n", ret, strerror(ret));
return 0;
}
void* thread2_entry(void* input)
{
printf("hello from 2\n");
printf("exit from 2.....\n");
return 0;
}
int main(void)
{
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, thread1_entry, NULL);
ret2 = pthread_create(&thread2, NULL, thread2_entry, NULL);
if (ret1 || ret2)
{
printf("error-%d-%d\n", ret1,ret2);
}
else
{
pthread_join(thread1, NULL);
}
return 0;
}
The output might be inconsistent(due to scheduling?), and the weirdest part is that the printf in thread 2 might be duplicated.
$ ./a.out
hello from 2
exit from 2.....
hello from 1-0-Success
$ ./a.out
hello from 1-0-Success
hello from 2
exit from 2.....
exit from 2.....
GCC Version:
$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.