Why am I getting these results in this small threaded program in C (LINUX)?
I have this little program that I found in the exam subject of the 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 on Ubuntu.
source to share
You don't join your threads before exiting main (). Add in the main()
following:
for(i=0; i<3; i+=1)
pthread_join(t[i], NULL);
Not attaching to threads results in undefined behavior where threads continue to execute while the program exits. undefined behavior is free to do, including duplicate printing. In the meantime, there is no need to worry about it.
Think of it this way, void*
which is passed to the stream is stored somewhere, and once you prematurely exit main, you can destroy the data that needs to be passed to the stream, after which it can take on any value (including duplicates ). But it's not even worth trying to explain it, since this behavior is undefined.
source to share
return
from a function is main
equivalent to calling exit
and terminates the entire process. Thus, its more or less random output is displayed on the screen. You must do one of the following
- attach all themes you created.
- call
pthread_exit
at the endmain
instead of callingexit
or withreturn
source to share