I have this small program that I found in an exam subject of an OS course.
void * func (void * p) {
int n = p;
printf("%d \n",n);
return NULL;
}
int main() {
int i;
pthread_t t[3];
for(i=0; i<3; i+=1)
pthread_create(&t[i] ,NULL, func, (void*)i);
return 0;
}
When I run it, I get the following results (with a new line after each digit):
1st run : 0 0
2nd run : 1 0 2 2
3rd run : 0 1 1
Why does it print 4 digits when I only create 3 threads. And how can it print duplicates?
The code is compiled with gcc in Ubuntu.

You do not join your threads before exiting main(). Add the following into main():
for(i=0; i<3; i+=1)
pthread_join(t[i], NULL);
Not joining the threads leads to undefined behavior when the threads continue to execute while the program is exiting. Undefined behavior is free to do anything, including printing duplicates.
Think of it this way, the void* that is passed to the thread is stored somewhere, and once you prematurely exit main you could be destructing the data to pass to the thread, at which point it can take on any value (including duplicate ones). But this isn't even worth trying to explain since it is undefined behavior.
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