Ask Question

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?

+3
Answers (1)
  1. 20 October, 18:28
    0
    Therefore, there are 4 possible values for c after both threads complete

    c = 4, 14, 3, 13

    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
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Suppose two threads execute the following C code concurrently, accessing shared variables a, b, and c: Initialization int a = 4; int b = 0; ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers