测试内存屏障存在:
#include <windows.h>
#include <stdio.h>
#include <assert.h>
typedef unsigned char u8;
typedef signed char s8;
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned int u32;
typedef signed int s32;
BOOL state[2];
u8 turn;
static u32 count = 0;
u32 val = 1000000;
#define MEM_BARRIER() do {__asm {mfence}}while(0)
//#define MEM_BARRIER()
void lock(int id)
{
state[id] = TRUE;
turn = 1 - id;
MEM_BARRIER();
while((turn == (1 - id)) && state[1 - id]); }
void unlock(int id)
{
state[id] = FALSE;
}
DWORD WINAPI ThreadProc(LPVOID args)
{
short id = *(int*)args;
u32 num = 0;
while(num++ < val) {
lock(id);
count++;
unlock(id);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread[2];
while(1) {
int i=0,j=1;
count = 0; turn = 0; state[1] = state[0] = FALSE;
hThread[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, &i, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask( hThread[0], 0x01 );
hThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, &j, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask( hThread[1], 0x02 );
ResumeThread(hThread[0]);
ResumeThread(hThread[1]);
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
if(count != 2000000) {
printf("-----------\n");
//__asm {int 3}
}
}
return 1;
}