switch语句中的竞争条件

时间:2016-04-01 05:13:47

标签: switch-statement race-condition

我试图理解以下example种族条件:

#include <sys/types.h>
#include <sys/stat.h>

int main(argc,argv){
   struct stat *sb;
   time_t timer;
   lstat("bar.sh",sb);
   printf("%d\n",sb->st_ctime);
   switch(sb->st_ctime % 2){
        case 0: printf("One option\n");
           break;
        case 1: printf("another option\n");
           break;
        default: printf("huh\n");
           break;
   }
   return 0;
}

解释说:

 It seems that the default case of the switch statement 
 should never be reached, as st_ctime % 2 should always 
 be 0 or 1. However, if st_ctime % 2 is 1 when the first 
 case is evaluated, the time may change and st_ctime % 2
 may be equal to 0 when the second case is evaluated. 
 The result is that neither case 1 or case 2 execute, 
 and the default option is chosen.

我无法理解这一部分: ...时间可能会改变,并且在评估第二种情况时st_ctime%2可能等于0。结果是案例1或案例2都不执行,并且选择了默认选项

该页面并不清楚这是适用于单线程还是多线程。

我读了相关的SO question,突出显示64位写入不是原子的。在上面的例子中,当switch正在评估条件时,时间会发生变化,sb->st_ctime % 2的评估是否仍然会出现在其他0 0r 1的情况下? (偶数或奇数?)单线程情况下是否存在问题?

0 个答案:

没有答案