Skip to content

Latest commit

 

History

History
74 lines (57 loc) · 1.89 KB

c26100.md

File metadata and controls

74 lines (57 loc) · 1.89 KB
description title ms.date ms.topic f1_keywords helpviewer_keywords ms.assetid
Learn more about: C26100
C26100
11/04/2016
reference
C26100
C26100
470ab2b2-5b55-424f-b192-3863a773c892

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.

Examples

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.