#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?
void *value — addreturn 0;. You don't wait for the threads to complete; that may be a factor in the problem, though I reserve judgement on that. - Jonathan Lefflerflockfile()andfunlockfile(). That page says: All functions that reference (FILE *) objects, except those with names ending in_unlocked, shall behave as if they useflockfile()andfunlockfile()internally to obtain ownership of these (FILE *) objects. Thus, if thread 1 is executingprintf(), all other threads are locked out from accessingstdoutuntil thread 1's call is effectively complete (it has calledfunlockfile(stdout)). - Jonathan Leffler