Sbiera Bogdan
Sbiera Bogdan

Reputation: 346

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

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

Upvotes: 3

Views: 296

Answers (2)

JaredC
JaredC

Reputation: 5300

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.

Upvotes: 7

Jens Gustedt
Jens Gustedt

Reputation: 78903

return from the main function is equivalent to a call to exit and terminates the whole process. So its more or less random which output makes it through to your screen. You should do one of the following

  • join all threads that you create
  • call pthread_exit at the end of main instead of calling exit or using return

Upvotes: 2

Related Questions