C26100

警告 C26100: 竞争条件。变量 <var> 应受到锁定 <lock>。

_Guarded_by_注释在代码中的指定的锁,以保护共享的变量使用。违反保护合同时,将生成警告 C26100。

示例

下面的示例生成警告 C26100,因为没有违反_Guarded_by_合同。

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); 
} 

本示例还生成警告 C26100,因为它在函数中使用了不正确的锁Unsafe2。