_ReadWriteBarrier
Visual Studio .NET 2003
Microsoft Specific
_ReadWriteBarrier effectively blocks an optimization of reads and writes to global memory. This can be useful to ensure the state of global variables at a particular point in your code for multithreaded applications.
// cpp_intrin_ReadWriteBarrier.cpp
// compile with: /MD /O2
// add /DUSE_BARRIER to see different results
#include <stdio.h>
#include <process.h> // _beginthread
#include <windows.h>
extern "C" void _ReadWriteBarrier();
#pragma intrinsic(_ReadWriteBarrier)
int G;
int i;
volatile int ReleaseF = 0, WaitF = 0;
void f(void *p)
{
G = 1;
#ifdef USE_BARRIER
_ReadWriteBarrier();
#endif
WaitF = 1;
while (ReleaseF == 0);
G = 2; // Without barrier, the optimizer could remove 'G = 1'...
}
int main()
{
_beginthread(f, 0, NULL); // New thread
while (WaitF == 0) // Wait for change in var waitF
Sleep(1);
if (G == 1)
puts("G is equal to 1, as expected.");
else
puts("G is NOT equal to 1!");
ReleaseF = 1;
}
Output
G is NOT equal to 1!
END Microsoft Specific