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); 
} 
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top