Q132: Output of the following multithreaded program?

Question #132: What will be the output of the following program?

#include <pthread.h>

#define NUM_THREADS 4

void *work(void *i){

  printf("Hello, world from %i\n", pthread_self());

  pthread_exit(NULL);

}

int main(int argc, char **argv){

  int i;

  pthread_t id[NUM_THREADS];

  for(i = 0; i < NUM_THREADS; ++i){

    if(pthread_create(&id[i], NULL, work, NULL)){

      printf("Error creating the thread\n"); exit(19);

    }

  }

  printf("After creating the thread. My id is: %i\n",

  pthread_self());

  return 0;

}

A) Hello, world from 1

Hello, world from 3

Hello, world from 4

After creating the thread. My id is: 2

 

B) Hello, world from 3

Hello, world from 2

Hello, world from 4

After creating the thread. My id is: 2

After creating the thread. My id is: 3

After creating the thread. My id is: 4

 

C) Hello, world from 4

Hello, world from 3

Hello, world from 2

After creating the thread. My id is: 1

 

D) Can’t predict

Solution: The correct answer is D. Thread inter-leavings cannot be predicted because of concurrency.