_crtl.h
#pragma once
#include <windows.h>
#include <concrt.h>
class _crtl
{
private:
int flags;
HANDLE m_event;
public:
void Enter();
void Leave();
_crtl(void);
~_crtl(void);
};
_crtl.cpp //临界区类
#include "StdAfx.h"
#include "_crtl.h"
_crtl::_crtl(void)
{
flags = 0;
m_event = CreateEvent(0,1,1,0);
}
_crtl::~_crtl(void)
{
}
void _crtl::Enter()
{
int t = (int)&this->flags;
Fr: __asm push eax;
__asm mov eax,t;
__asm lock bts dword ptr[eax], 0;
__asm pop eax;
__asm jc Bs;
//ResetEvent(m_event);
return ;
Bs:
Sleep(0);
//WaitForSingleObject(m_event,INFINITE);
__asm jmp Fr;
}
void _crtl::Leave()
{
flags = 0;
//Sleep(0);
//SetEvent(m_event);
}
临界区 //主函数
#include "StdAfx.h"
#include <process.h>
#include <iostream>
#include "_crtl.h"
#define THREAD_COUNT 100
int asdf = 0;
using namespace std;
_crtl* m_ctl = new _crtl;
unsigned int _stdcall fun(void*);
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int thread_ID;
for (int i=0;i<THREAD_COUNT;i++)
{
HANDLE m_ID = (HANDLE)_beginthreadex(NULL, 0, fun, 0, 0, &thread_ID);
}
getchar();
return 0;
}
unsigned int _stdcall fun(void*)
{
for (int i=0;i<30;i++)
{
m_ctl->Enter();
cout<<asdf<<" ";
asdf++;
m_ctl->Leave();
}
return 0;
}