Vineet Kaushik Vineet Kaushik - 2 months ago 10
C++ Question

Can't understand this basic threads behaviour

I am studying about threads and concurrent programming. Tried this basic example from what was provided in class:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_THREADS 8

void *printGoGators(void *noArg)
{
printf("Go Gators!\n");
return NULL;
}

int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;
for (t = 0; t < NUM_THREADS; t++)
{
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t],
NULL,
printGoGators,
NULL);
if(rc)
{
printf("ERROR %d", rc);
exit(-1);
}
}
pthread_exit(NULL);
}


This code produces the following output. :

Creating thread 0
Creating thread 1
Go Gators!
Creating thread 2
Go Gators!
Creating thread 3
Go Gators!
Creating thread 4
Go Gators!
Creating thread 5
Go Gators!
Creating thread 6
Go Gators!
Creating thread 7
Go Gators!
Go Gators!


Why is
Go Gators!
not printed directly after its corresponding
Creating thread #
for all threads?
Please help!

Answer

If your code looked like this, then the output would be in the order you expect:

for (t = 0; t < NUM_THREADS; t++)
    {
      printf("Creating thread %d\n", t);
      printGoGators(NULL);
    }

So, you're making an assumption that threads will execute in the same order that they are created. However, that assumption is incorrect - threads may execute in any order.