in Operating System edited by
375 views
0 votes
0 votes

Consider the following multi threaded code.

volatile static int flag1= 0, flag2= 0;

// code for thread 1 (or T1)

flag1 = 1;
if (flag2==0) 
    code1();
    
// end of code for T1


    
// code for thread 2 (or T2)

flag2 = 1;
if (flag1 == 0) 
    code2();

// end of code for T2

 

Which of the following is true ?

What can happen on a mono-processor machine?

  1. code1() is invoked, but not code2().
  2. code2() is invoke, but not code1().
  3. no method is invoked.
  4. both methods cannot be invoked!

Also, what will be the answer if we remove the volatile type from the flags.

 

in Operating System edited by
by
375 views

1 Answer

2 votes
2 votes
Thread1 Thread2
  1. flag1 = 1;
  2. if (flag2==0)
  3. code1();
  1. flag2 = 1;
  2. if (flag1 ==0)
  3. code2();

 

Initially flag1 = flag2 = 0;

Case 1: If T1 goes first and preemption occurs after line 1, then both threads are in a starvation state.

Case 2: If T1 runs completely and then T2 runs, then code1() executes but not code2().

Case 3: If T2 runs completely and then T1 runs, then code2() executes but not code1().

So, the answer is 1,2,3.

1 comment

and what if we remove volatile from the flags?
0
0

Related questions