문제

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