Here is an example where we combine the previous programs to create a multi-threaded mutex based program. If you havent already seen, then please check out the
Singleton class and
Multi-Threading with Thread Sync.
We are going to have some .h files in this example.
Lock.h
#if !defined _LOCK_H_
#define _LOCK_H_
#include "Mutex.h"
class Lock
{
public: Lock ( Mutex & mutex )
: _mutex(mutex)
{
_mutex.Acquire();
} ~Lock ()
{
_mutex.Release();
}
private:
Mutex & _mutex;
};
#endif
Mutex.h
#if !defined _MUTEX_H_
#define _MUTEX_H_
class Mutex
{
friend class Lock;
public:
Mutex () { InitializeCriticalSection (& _critSection); }
~Mutex () { DeleteCriticalSection (& _critSection); }
private:
void Acquire ()
{
EnterCriticalSection (& _critSection);
}
void Release ()
{
LeaveCriticalSection (& _critSection);
}
CRITICAL_SECTION _critSection;
};
#endif
Singleton.h
#include "Lock.h"
#include "Mutex.h"
class aSingletonClass
{
public: static aSingletonClass *getInstance( void )
{ if(!instance_)
instance_ = new aSingletonClass;
return instance_;
} static void deleteInstance( void )
{
if(instance_)
delete instance_;
instance_ = NULL; }
void printSomething(char *name, int count)
{
Lock guard(mutex_);
std::cout << name << " loop " << count << std::endl;
}
private: static aSingletonClass *instance_; aSingletonClass() {}; ~aSingletonClass() {}; aSingletonClass(const aSingletonClass&);
Mutex mutex_;
};
Thread.cpp
#include <windows.h>
#include <process.h>
#include <iostream>
#include "Singleton.h"
using namespace std;
aSingletonClass* aSingletonClass::instance_ = NULL;
void Func1(void *);
void Func2(void *);
int main()
{
HANDLE hThreads[2];
aSingletonClass *someVar = NULL; someVar = aSingletonClass::getInstance(); hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL); WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
cout << "Main exit" << endl;
return 0;
}
void Func1(void *P)
{
int Count;
for (Count = 1; Count < 11; Count++)
{
aSingletonClass::getInstance()->printSomething("Func1", Count);
}
return;
}
void Func2(void *P)
{
int Count;
for (Count = 10; Count > 0; Count--)
{
aSingletonClass::getInstance()->printSomething("Func2", Count);
}
return;
}
The Output is as follows: