What would get printed in the following C code and why?
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void *worker(void *arg){
int *data = (int *) arg;
*data = *data +1;
printf(“Data is %dn”, *data);
return (void *) 42;
}
int data;
int main(){
int status = 0;
data = 0;
pthread_t thread;
pid_t pid = fork();
if (pid == 0){
pthread_create(&thread, NULL, &worker, &data);
pthread_join(thread, NULL);
}
else{
pthread_create(&thread, NULL, &worker, &data);
pthread_join(thread, NULL);
pthread_create(&thread, NULL, &worker, &data);
pthread_join(thread, NULL);
wait(&status);
}
return 0;
}
Expert Answer
Output:
Data is 1
Data is 1
Data is 2
Explanation:
3 threads will create.
1st -> if(pid == 0) the first thread will create and it will call the worker and increment data value as 1.
2nd -> else block where 2 threads will start. 2 times worker will be called by pthread_create and data value increments from 0 to 1 and 1 to 2.