The technique of try finally is grate but the following code is a more C++
style aproach:
#include <windows.h>
template<typename LOCK_TYPE>
class Guard
{
protected:
LOCK_TYPE * lock_;
public:
Guard(LOCK_TYPE & lock) : lock_(&lock)
{
this->lock_->aquire();
}
~Guard()
{
this->lock_->release();
}
};
class CriticalSection
{
private:
CRITICAL_SECTION cs_;
public:
CriticalSection()
{
::InitializeCriticalSection(&this->cs_);
}
~CriticalSection()
{
::DeleteCriticalSection(&this->cs_);
}
void aquire(void)
{
::EnterCriticalSection(&this->cs_);
}
void release(void)
{
::LeaveCriticalSection(&this->cs_);
}
};
class Mutex
{
// kind of the same as CritcalSection class but using CreateMutex,
OpenMutex, etc...
};
CriticalSection g_cs;
//Mutex g_mtx;
int do_something(void)
{
Guard<CriticalSection> guard(g_cs);
//Guard<Mutex> guard(g_mtx);
// do something usefull and dont't butter about releasing the critical
// section because the Guard's template destructor will do it for you
// as soon as you leave this function whatever it happens.
// it is pretty generic because you can use not only critical sections
// but mutexes as well.
return 0;
}
int main(int argc, char * argv[])
{
return do_something();
}
Ivan Mejia C++ Dev.
"Jochen Kalmbach [MVP]" wrote:
Hi Carl!
how can I synchronize 2 threads using the 'lock'-equivalent that is
available in C# ?
If managed, you can use the same mechanism that C# uses: the
System.Threading.Monitor class - you just have to call the member functions
explicitly while the C# lock construct calls them for you.
Just as an addition, here is a small code-sample (because this will be
mostly implemented without the __try-__finally):
C#:
lock(obj)
{
// Some code
}
managed C++:
System::Threading::Monitor::Enter(obj);
__try
{
// Some code
}
__finally
{
System::Threading::Monitor::Exit(obj);
}
--
Greetings
Jochen
My blog about Win32 and .NET
http://blog.kalmbachnet.de/