214k views
2 votes
Suppose two threads execute the following C code concurrently, accessing shared variables a, b, and c: Initialization int a = 4; int b = 0; int c = 0; Thread 1 Thread 2 if (a < 0) { b = 10; c = b-a; a = -3; } else { c = b + a; } What is the total number of possible values for c after both threads complete? You can assume that reads and writes of the variables are atomic and that the order of statements within each thread is preserved in the code generated by the C compiler?

User Sophya
by
4.7k points

1 Answer

1 vote

Answer:

Therefore, there are 4 possible values for c after both threads complete

c = 4, 14, 3, 13

Step-by-step explanation:

Initialization:

int a = 4;

int b = 0;

int c = 0;

Thread 1:

if (a < 0)

{

c = b - a;

}

else

{ c = b + a; }

Thread 2:

b = 10;

a = -3;

We have to consider all the possible cases.

Case 1: a = 4, b = 0, c = 0

if (a < 0) false

{

c = b - a;

}

else

{ c = b + a; } c = 0 + 4 = 4

c = 4

Case 2: a = 4, b = 10, c = 0

if (a < 0) false

{

c = b - a;

}

else

{ c = b + a; } c = 10 + 4 = 14

c = 14

Case 3: a = -3, b = 0, c = 0

if (a < 0) true

{

c = b - a; c = 0 - (-3) = 3

}

else

{ c = b + a; }

c = 3

Case 4: a = -3, b = 10, c = 0

if (a < 0) true

{

c = b - a; c = 10 - (-3) = 13

}

else

{ c = b + a; }

c = 13

Therefore, there are 4 possible values for c after both threads complete

c = 4, 14, 3, 13

User Deeps
by
4.9k points