Note This is an old answer. C++11 contains better helpers that are more platform independent:
And other options like std::unique_lock, boost::unique_lock
Any RAII tutorial will do.
Here's the gist: (also on http://ideone.com/kkB86)
// stub mutex_t: implement this for your operating system
struct mutex_t
{
void Acquire() {}
void Release() {}
};
struct LockGuard
{
LockGuard(mutex_t& mutex) : _ref(mutex)
{
_ref.Acquire(); // TODO operating system specific
}
~LockGuard()
{
_ref.Release(); // TODO operating system specific
}
private:
LockGuard(const LockGuard&); // or use c++0x ` = delete`
mutex_t& _ref;
};
int main()
{
mutex_t mtx;
{
LockGuard lock(mtx);
// LockGuard copy(lock); // ERROR: constructor private
// lock = LockGuard(mtx);// ERROR: no default assignment operator
}
}
Of course you can make it generic towards mutex_t
, you could prevent subclassing.
Copying/assignment is already prohibited because of the reference field
EDIT For pthreads:
struct mutex_t
{
public:
mutex_t(pthread_mutex_t &lock) : m_mutex(lock) {}
void Acquire() { pthread_mutex_lock(&m_mutex); }
void Release() { pthread_mutex_unlock(&m_mutex); }
private:
pthread_mutex_t& m_mutex;
};