2,797 views
5 votes
5 votes
const int n = 5;
int count = 0;
void test(){
    for i = 1 to n
    count += 2;
}
main()   {
    Par begin 
        test();
        test();
        test();
    Par end   
}


What can be the maximum and minimum value of count after completion of the program?
 

4 Answers

14 votes
14 votes

Minimum should be 4. Maximum should be 30.

As explained, it's read, increment count and store(3 steps) during execution of :

count+=2;

3 test() calls with 5 iterations for each. For simplicity let's consider 3 processes P1, P2 and P3 will execute one test each.

P1: Test() call (first iteration): loads '0', increments it by 2, [gets preempted before storing it back]

P2: Allow all 5 iterations for test() to run. The count value will now be 10 

P3: 4 iterations of third test() runs normally and gets preempted. So, now the value of count is 18.

Now,  P1 is starts again from where it left off. It has count value of 2 incremented locally. It stores back 2 and gets preempted.

Now, P3 resumes execution of it's final iteration. It loads the value of count as 2, increments it to 4 and gets preemted

NowP1 executes remaining 4 iterations making the value of count as 10.

Finally, P3 executes the 'store' for it's last iteration. It stores back 4 (since it has count value as 4 locally incremented) 

So, minimum turns out to be 4

The maximum will be 30 (execution happens sequentially)

6 votes
6 votes
Count += 2  treated as three instruction,

1. Read count

2. count + 2            //increment locally

3. Store                  // Globally

All 3 test() inside par begin par end means these function executes concurrently.

Program execution for max value.of count : run serially all Test(). Count becomes 30..

Now for minimum value :

Execute each test() for i=1 utill count +2 ..

Each test() increment count value to count +2 LOCALLY & still waiting for all test() to increment der local count by 2.

After incrementing local count let 1st test write count to 2 GLOBALLY.

Then 2nd test write count to 2 (because count +2 done locally so count value is still 2 for this test() ) . It overwrites count value by 2.

Then 3rd test() executes in same way as 2nd test() .

For n=1 all 3 test() executed and count value is 2..

 

Do same same for n=2,3,4,5

Final value of count is 10.
0 votes
0 votes
MIn is 10 when each thread reads the same count value each time and updated

Max is 30 when threads run one after the other.