Unable to understand pthread_create() behaviour in the following program?

Viewed 116
#include <stdio.h>
#include <pthread.h>

void *thread_func(void *arg)
{
        printf("hello, world \n");
        return 0;
}

int main(void)
{
        pthread_t t1, t2;

        pthread_create(&t1, NULL, thread_func, NULL);
        pthread_create(&t2, NULL, thread_func, NULL);

        printf("t1 = %d\n",t1);
        printf("t2 = %d\n",t2);

        return 0;
}

The above program creates two threads, where each thread prints "Hello World".

So, as per my understanding, the "Hello world" should print a maximum 2 times.

However, while executing the same program multiple times(back to back), there are scenarios where "Hello world" is being printed more than 2 times. So I am unclear how it is getting printed an unexpected number of times?

Here are the sample outputs:

[rr@ar ~]$ ./a.out
t1 = 1290651392
t2 = 1282258688
hello, world
hello, world


[rr@ar ~]$ ./a.out
t1 = 1530119936
t2 = 1521727232
hello, world
hello, world
hello, world

As shown above, after executing the program for many times, "hello, world" is printed 3 times. Can anyone please advise how come it got printed 3 times?

3 Answers
Related