测试内存屏障存在

测试内存屏障存在:


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值