位测试临界区实现

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值