Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
C26100
Collapse the table of content
Expand the table of content

C26100

warning C26100: Race condition. Variable <var> should be protected by lock <lock>.

The _Guarded_by_ annotation in the code specifies the lock to use to guard a shared variable. Warning C26100 is generated when the guard contract is violated.

The following example generates warning C26100 because there is a violation of the _Guarded_by_ contract.

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

The contract violation occurs because an incorrect lock is used in the function Unsafe. In this case, gCS is the correct lock to use.

Occasionally a shared variable only has to be guarded for write access but not for read access. In that case, use the _Write_guarded_by_ annotation, as shown in the following example.

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

This example also generates warning C26100 because it uses an incorrect lock in the function Unsafe2.

Show:
© 2015 Microsoft