模拟ATM取钱动作,不加锁可能为负数,加了锁就不会了
// test.cpp : Defines the entry point for the console application.//
#include "stdafx.h"
#include "../../include/ace/ACE.h"
#include "../../include/ace/Log_Msg.h"
#include "../../include/ace/Singleton.h"
#include "../../include/ace/Null_Mutex.h"
#include "../../include/ace/OS.h"
#include "../../include/ace/Thread_Mutex.h"
#include "../../include/ace/Global_Macros.h"
#pragma comment( lib, "libace32.lib")
class config_data
{
public:
config_data();
~config_data();
void add();
};
config_data::config_data()
{
ACE_DEBUG((LM_INFO, ACE_TEXT("[%M][%T][%t] load route: %s\n"), "config_data()"));
}
config_data::~config_data()
{
ACE_DEBUG((LM_INFO, ACE_TEXT("[%M][%T][%t] load route: %s\n"), "~config_data()"));
}
void config_data::add()
{
ACE_DEBUG((LM_INFO, ACE_TEXT("[%M][%T][%t] load route: %s\n"), "add()"));
}
typedef ACE_Singleton<config_data,ACE_Null_Mutex> GAME_CONFIG;
ACE_Thread_Mutextableptr_storm_lock;
#include "ace/Log_Msg.h"
#include "ace/OS.h"
#include "ace/Thread.h"
#include "ace/Task.h"
int num=0;
class CommandHandler: public ACE_Task_Base
{
private:
static int nThreadNum;
public:
virtual int svc(void)
{
int nThreadID = 0;
int i = 0;
nThreadNum++;
nThreadID = nThreadNum;
ACE_DEBUG( (LM_INFO, ACE_TEXT("thread[%t] %d start\n"), nThreadID) );
ACE_OS::sleep(1);
while(i <= 100)
{
i++;
ACE_OS::sleep(1);
{
num++;
{
ACE_DEBUG( (LM_INFO, ACE_TEXT("thread[%t] num = %d \n"), num) );
}
}
}
return nThreadID;
}
};
class CommandHandler1: public ACE_Task_Base
{
public:
virtual int svc(void)
{
int nThreadID = 0;
int i = 0;
ACE_DEBUG( (LM_INFO, ACE_TEXT("thread[%t]start\n")) );
ACE_OS::sleep(1);
while(i <= 100)
{
i++;
{
ACE_GUARD_RETURN(ACE_Thread_Mutex,g,tableptr_storm_lock,-1);
int aa=num;
if(num>0)
{
ACE_OS::sleep(2);
num-=aa;
}
ACE_DEBUG( (LM_INFO, ACE_TEXT("--thread[%t] num = %d \n"), num) );
}
ACE_OS::sleep(1);
}
return nThreadID;
}
};
int CommandHandler::nThreadNum = 0;
int _tmain(int argc, _TCHAR* argv[])
{
GAME_CONFIG::instance()->add();
GAME_CONFIG::instance()->add();
ACE_DEBUG((LM_INFO, ACE_TEXT("[%M][%T][%t] load route: %s\n"), "test"));
int nReturn = 0;
CommandHandler cmd;
CommandHandler1 cmd1;
nReturn = cmd.activate(THR_NEW_LWP|THR_JOINABLE,1);//存钱线程
ACE_OS::sleep(1);
cmd1.activate(THR_NEW_LWP|THR_JOINABLE,20);//取钱线程,假设有20个人在不同的ATM机器上取
if(nReturn != 0)
{
ACE_DEBUG( (LM_ERROR, ACE_TEXT("failed to active this thread[%d] %p\n"), nReturn, ACE_TEXT("active")) );
return -1;
}
/*ACE_OS::sleep(10);
ACE_DEBUG( (LM_INFO, ACE_TEXT("Suspend this thread ......\n")) );
cmd.suspend();
ACE_OS::sleep(10);
ACE_DEBUG( (LM_INFO, ACE_TEXT("Resume this thread ......\n")) );
cmd.resume();*/
cmd.wait();
return 0;
}
页:
[1]