Question

me and my friends came across this example code online and we are arguing wether it implements a critical section or not.. Our opinions are going back and forth so we thought about asking stackoverflow.

So, do we implement a critical section here or not?

int flagga[2]; 

void task0(void){ 
 while(1){ 
 /* some code */ 
 flagga[0]=true; 
 while(flagga[1]==true) /*do nothing*/; 
 /* critical sektion */ 
 flagga[0]=false; 
 } 
} 

void task1(void){ 
 while(1){ 
 /* some code */ 
 flagga[1]=true; 
 while(flagga[0]==true) /*do nothing*/; 
 /* critical section */ 
 flagga[1]=false; 
 } 
} 

void main(void){ 
 flagga[0]=flagga[1]=false; 
 startThread(task0); 
 startThread(task1); 
 while(1); 
} 
Was it helpful?

Solution

It suffers from possible starvation: if neither task gets to the inner while before the other has set its flagga to true (which can happen if you stickily alternate between statements in each task), both will get stuck in its inner while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top