C26100

警告 C26100:争用条件。变量 <var> 应由 <锁定> 锁定保护。

代码中的 _Guarded_by_ 注释指定用于保护共享变量。当违反协定时,会生成 C26100 警告。

示例

因为有冲突 _Guarded_by_ 协定,下面的示例生成警告 C26100。

CRITICAL_SECTION gCS; 

_Guarded_by_(gCS) int gData; 

typedef struct _DATA { 
   _Guarded_by_(cs) int data; 
   CRITICAL_SECTION cs; 
} DATA; 

void Safe(DATA* p) { 
   EnterCriticalSection(&p->cs); 
   p->data = 1; // OK 
   LeaveCriticalSection(&p->cs); 
   EnterCriticalSection(&gCS); 
   gData = 1; // OK 
   LeaveCriticalSection(&gCS); 
} 

void Unsafe(DATA* p) { 
   EnterCriticalSection(&p->cs); 
   gData = 1; // Warning C26100 (wrong lock) 
   LeaveCriticalSection(&p->cs); 
}

因为在函数 Unsafe中的非正确锁定,发生协定违规。在这种情况下,gCS 是正确锁定的使用。

又是共享变量只在写入访问被保护,读取访问时不被保护。如下例所示,在这种情况下,请使用 _Write_guarded_by_ 注释。

CRITICAL_SECTION gCS; 

_Guarded_by_(gCS) int gData; 

typedef struct _DATA2 { 
   _Write_guarded_by_(cs) int data; 
   CRITICAL_SECTION cs; 
} DATA2; 

int Safe2(DATA2* p) { 
   // OK: read does not have to be guarded 
   int result = p->data; 
   return result; 
} 

void Unsafe2(DATA2* p) { 
   EnterCriticalSection(&gCS); 
   // Warning C26100 (write has to be guarded by p->cs) 
   p->data = 1; 
   LeaveCriticalSection(&gCS); 
} 

此示例还指出因为函数 Unsafe2使用了不正确锁定,生成了 C26100 警告。