in this post used Mutex for Syncronization
there create three class Lock,Mutex and Singleton class
// multiThreading.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Windows.h"
#include "process.h"
#include "iostream"
using namespace std;
class Mutex
{
public:
Mutex()
{
InitializeCriticalSection(& _CritSection);
}
~Mutex()
{
DeleteCriticalSection(& _CritSection);
}
private:
friend class Lock;
CRITICAL_SECTION _CritSection;
BOOL mutexAcquire;
void Acquire()
{
EnterCriticalSection(& _CritSection);
}
void Release()
{
LeaveCriticalSection(& _CritSection);
}
};
class Lock
{
public:
Lock ( Mutex & mutex ) : _mutex(mutex)
{
_mutex.Acquire();
}
// Release the state of the semaphore
~Lock ()
{
_mutex.Release();
}
private:
Mutex & _mutex;
};
class Singleton
{
private:
static Singleton *pInstance;
Singleton(){}
~Singleton(){}
Singleton(const Singleton&){};
Mutex mutex_;
public:
static Singleton *getInstance(void)
{
if(!pInstance)
{
pInstance=new Singleton;
}
return pInstance;
}
static void DeleteInstance()
{
if(pInstance)
{
delete pInstance;
}
pInstance =NULL;
}
void PrintSomething(char *name,int count)
{
Lock guard(mutex_);
std::cout<<name<<" loop "<<count<<"\n";
}
};
void FunOne(void * p)
{
int count ;
for(count=0;count<11;count++)
{
Singleton::getInstance()->PrintSomething("FunOne",count);
}
}
void FunTwo(void * p)
{
int count1 ;
for (count1=10;count1>0;count1--)
{
Singleton::getInstance()->PrintSomething("FunTwo",count1);
}
}
Singleton* Singleton::pInstance = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread[2];
Singleton *someVar=NULL;
someVar= Singleton::getInstance();
hThread[0]=(HANDLE)_beginthread(FunOne,0,NULL);
hThread[1]=(HANDLE)_beginthread(FunTwo,0,NULL);
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
cout<<"Main thread Exit"<<endl;
return 0;
}
Comments
Post a Comment