0

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.
AsaMyth
  • 1
  • 4

1 Answers1

0

not really pretty, but you could have a global bool that tells you whether second thread has written stuff or not. So,

void* thread1_entry(void* input)
{   
    while (!second_ended){}
    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");

    second_ended = true;
    return 0;
}

as to why it happens, that just how threads work - its really impossible to tell which one will start first.

Murksiuke
  • 27
  • 6
  • Yeah, I know whether thread1 or thread2 get to run is undefined in this case. I'm curious to know that why the second printf in thread2 may be called twice if I repeatedly run the program. – AsaMyth Mar 30 '19 at 14:54
  • I changed the question from "inconsistent" to "duplicated". – AsaMyth Mar 30 '19 at 15:04