Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get these results in this small program with threads in C (LINUX)?

Tags:

c

linux

pthreads

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.

screenshot of the terminal

like image 724
Sbiera Bogdan Avatar asked Dec 19 '25 01:12

Sbiera Bogdan


1 Answers

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.

like image 167
JaredC Avatar answered Dec 21 '25 15:12

JaredC