拷贝一下代码,留作自己备份吧,不注释啦
#include <Windows.h>
#include <process.h>
void lock_visit(int & p)
{
_asm
{
push ecx
push eax
xor ecx , ecx
mov eax, p
lock_judge: xchg ecx, dword ptr[eax]
jecxz lock_judge
pop eax
pop ecx
}
}
void unlock_visit(int &p)
{
_asm
{
push ecx
push eax
mov ecx, 1
mov eax, p
xchg ecx, dword ptr[eax]
pop eax
pop ecx
}
}
int g_lock_var = 1;
int g_times = 0;
void lock_print(void * d)
{
while(1)
{
lock_visit(g_lock_var);
printf("the %d times, thread:%d \n", ++g_times, GetCurrentThreadId());
unlock_visit(g_lock_var);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
_beginthread(lock_print, 0, 0);
_beginthread(lock_print, 0, 0);
_beginthread(lock_print, 0, 0);
_beginthread(lock_print, 0, 0);
Sleep(1000 * 1000);
return 0;
}