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.

Q84: Fork behavior

Question 84: What will be the output of the following program:

if ( fork() )

{ printf(“Parent Process\n”);

wait(NULL);

printf(“Waited for child\n”);

}

else

{ printf(“Child Process\n”);

}

1. Parent Process

Child Process

Waited for child

2. Child Process

Parent Process

Waited for child

3. Parent Process

Waited for child

Child Process

4. Both A and B are possible

Solution: Since both parent and child process can execute first depending on the scheduling policy, it is indeterminate. The only thing is that child process has to be killed before parent can go ahead of wait(). The correct answer is option 4.