Skip to content
Advertisement

output in Line A and Line B?

What would be the output in Line A and Line B?
Do you think there is synchronization problem in updating the variable value?

#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
int value = 100;

void *thread_prog(void *param);

int main(int argc, char *argv[]) {
   pthread_t tid;
   pthread_create(&tid,NULL,thread_prog,NULL);
   pthread_join(tid, NULL);
   value= value + 100;
   printf("Parent value = %dn",value); //Line A
}

void *thread_prog(void *param) {
   value = value + 100;
   printf("Child value = %dn",value); // Line B
   pthread_exit(0);
} 

Advertisement

Answer

Child value is 200 and Parent value is 300 always. pthread_join causes the main thread to wait until the other thread finishes executing. Both threads are acting on the same global variable. So the thread_prog thread increments value and prints 200. The main thread then increments value and prints 300.

The 2 threads aren’t exactly parent and child threads. I believe based on your question, that you mean to use the fork method instead of pthread_create

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement