警告 C26100怎么解决_是什么原因

争用条件。 变量“var”应受锁定“lock”保护。

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

代码分析名称:RACE_CONDITION

示例

下面的示例将生成警告 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 中使用了错误的锁。

posted @ 2025-07-01 20:54  富美  阅读(10)  评论(0)    收藏  举报