#include <windows.h> #include <iostream> using namespace std; class CMySync { public: CMySync() { } virtual ~CMySync() { } virtual void Lock() { } virtual void Unlock() { } }; class CMyCriticalSection : public CMySync { CRITICAL_SECTION m_cs; public: CMyCriticalSection() { InitializeCriticalSection(&m_cs); } virtual ~CMyCriticalSection() { DeleteCriticalSection(&m_cs); } virtual void Lock() { EnterCriticalSection(&m_cs); } virtual void Unlock() { LeaveCriticalSection(&m_cs); } }; class CMyEvent : public CMySync { HANDLE m_hEvent; public: CMyEvent(LPSECURITY_ATTRIBUTES lpSA = NULL,LPCSTR lpName = NULL) { m_hEvent = CreateEvent(lpSA,FALSE,TRUE,lpName); } virtual ~CMyEvent() { if(m_hEvent) CloseHandle(m_hEvent); } virtual void Lock() { WaitForSingleObject(m_hEvent,INFINITE); } virtual void Unlock() { SetEvent(m_hEvent); } }; class CMyMutex : public CMySync { HANDLE m_hMutex; public: CMyMutex(LPSECURITY_ATTRIBUTES lpSA = NULL,LPCSTR lpName = NULL) { m_hMutex = CreateMutex(lpSA,FALSE,lpName); } virtual ~CMyMutex() { if(m_hMutex) CloseHandle(m_hMutex); } virtual void Lock() { WaitForSingleObject(m_hMutex,INFINITE); } virtual void Unlock() { ReleaseMutex(m_hMutex); } }; class CAutoSync { CMySync *m_pSync; public: CAutoSync(CMySync *pSync) : m_pSync(pSync) { m_pSync->Lock(); } ~CAutoSync() { m_pSync->Unlock(); } }; int nTickets = 100; //CMyCriticalSection g_Sync; CMyCriticalSection *g_pSync = new CMyCriticalSection(); DWORD WINAPI ThreadProc1(LPVOID lpParameter) { while(1) { //g_Sync.Lock(); CAutoSync m_Sync(g_pSync); if(nTickets>0) cout<<"Thread1 sell ticket: "<<nTickets--<<endl; //g_Sync.Unlock(); } } DWORD WINAPI ThreadProc2(LPVOID lpParameter) { while(1) { //g_Sync.Lock(); CAutoSync m_Sync(g_pSync); if(nTickets>0) cout<<"Thread2 sell ticket: "<<nTickets--<<endl; //g_Sync.Unlock(); } } void main(int argc,TCHAR*argv[]) { HANDLE hThread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc1,NULL,0,NULL); HANDLE hThread2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc2,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); Sleep(4000); }