elias rizik elias rizik - 5 months ago 31
C Question

can somone explain the solution of these two questions (c program,mutex,threads)?

I have a question and its answers from an old exam but I don't understand the solution. Can someone explain it to me?

Given this C program:

int a = 0;
int b = 0;
pthread_mutex_t m;

void * f()
_________________ (Empty Line for question number 2)
a = a + 1;
b = b + 1;
printf("a = %d, b = %d\n", a, b);
return NULL;

int main() {
pthread_t t1, t2;
pthread_mutex_init(&m, NULL);
pthread_create(&t1, NULL, &f, NULL);
pthread_create(&t2, NULL, &f, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;

  1. How many different print outputs can the program emit? (the answer is 3)

  2. What code you can add at the Empty Line to reduce the various print options to 1? (the answer is
    int a=0;

How should I have arrived at these answers?


I'll just assume that you mean different value combinations of a and b which are printed, by "print options".

So at the start you have a and b = 0

Then you create the threads and there is a racing condition on a so the result is not deterministic. What could happen:

t1:read a=0  write a=0+1
t1:read b=0  write b=0+1
t1:print `a=1, b=1`
t2:read a=1 write a=1+1
t2:read b=1 write b=1+1
t2:print `a=2, b=2`

the other thing that could happen:

t1: read a =0
t2: read a =0
t1: write a =0+1
t2: write a =0+1
t1: read b=0  write b=0+1
t1: print `a=1, b=1`
t2: read b=1 write b=1+1
t2: print `a=1, b=2`

This is one possibility. The read and writes of a can happen at anytime. But these are examples how different outputs can happen. t1 and t2 are also interchangeable. There is no guarantee that t1 executes first.

The second answer hides the global a with a local a which can not be overwritten by the other thread. So the output would always be.

a=1, b=1 a=1, b=2

edit: forgot the third print scenario for the first question

a=2, b=1 a=2, b=2

this happens if a is read and written separately(first read write t1 then read write t2) but before the first thread does the print.