Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What would get printed in the following C code and why ? #include <pthread.h> #i

ID: 3867472 • Letter: W

Question

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 %d ", *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;

}

Explanation / 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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote