共用方式為


警告 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 式 中使用不正確的鎖定。