
int g_counter = 0;
readonly Object r_LockA = new Object();
void IncrementCounter()
{
lock(r_LockA)
{
g_counter++;
}
}
void DecrementCounter()
{
lock(r_LockA)
{
g_counter--;
}
}
int g_counter = 0;
final Object r_LockA = new Object();
void IncrementCounter()
{
lock(r_LockA)
{
g_counter++;
}
}
void DecrementCounter()
{
synchronized(r_LockA)
{
g_counter--;
}
}
I have included a "dummy" function called DecrementCounter() here just to show that many blocks of code
can/are controlled by the same "lock" for a resource. I.E. if one thread is inside a block of code protected
by lock "A" then no other threads can be in ANY block of code protected by lock "A". Also, you mustn't have
the resource (g_counter in this case) changed in one place inside the lock only to have another function change #
it without a lock. The rule of thumb is: If you lock on it in one place, you lock on it in all places.
class Mutex
{
public:
Mutex();
~Mutex();
void Enter();
void Exit();
private:
HANDLE _hMutex;
}
Mutex::Mutex()
{
_hMutex = CreateMutex(
NULL, // lpSecurityAttributes - Ignoring Security
TRUE // bInitialOwner - We own it
"MyMutextWithUniqueName"); // lpName - Unique Name
}
Mutex::~Mutex()
{
CloseHandle(_hMutex);
}
Mutex::Enter()
{
WaitForSingleObject(_hMutex, INFINITE);
}
Mutex::Exit()
{
ReleaseMutex(_hMutex);
}
This class is used to house the Win32 Mutex. We then use the Lock class to be able to use it
class Lock
{
public:
Lock(Mutex* pMutex);
~Lock();
private:
Mutex* _pMutex;
}
Lock::Lock(Mutex* pMutex)
{
_pMutex = pMutex;
_pMutex->Enter();
}
Mutex::~Mutex()
{
_pMutex->Exit();
}
These classes together then make it easy to use:
class Test
{
public:
void IncrementCounter();
void DecrementCounter();
private:
int _counter;
Mutex _mutex;
}
Test::IncrementCounter()
{
Lock lock(&_mutex);
_counter++
}
Test::DecrementCounter()
{
Lock lock(&_mutex);
_counter++
}
The nice thing about using the lock class it it acquires the lock on declaration, and releases it
automatically after the funtion has completed because the Lock classes' destructor is called by the
C++ implementation.
Privacy Policy
©2008 DebugInspector. All rights reserved