共用方式為


C26100

警告 C26100: 競爭情形。 變數<var> 應該被鎖定 <lock>所保護。

在程式碼的 _Guarded_by_ 標記法指定鎖定使用嚴密監控共用變數。 When Guard 合約違反時,警告的 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); 
} 

因為它在函式 Unsafe2,使用一個無效的鎖定這個範例也會產生警告 C26100。