Note: This page has moved here. You will be redirected automatically, but please update your bookmarks.

Implementing a lock keyword in C++

There are two types of programmers in the world, which I like to call "the LEGO™ type" and "the Playmobile™ type", for reasons which will become clear in a short while. C# fans like to point out how the language offers nice syntax for often-used constructs, such as protecting a certain block of code with a lock:
lock (m_mutex)
{
    // my protected code here
}

C++ doesn't have a lock keyword, but you can make one yourself. Given a Mutex class which has Lock() and Unlock() member functions (and perhaps an IsLocked() for convenience) most C++ programmers would immediately write an AutoLock, somewhat like this:
class AutoLock
{
public:
    AutoLock(Mutex& m): m_mutex(m)  { m_mutex.Lock(); }
    ~AutoLock()                     { m_mutex.Unlock(); }
    operator bool()                 { return m_mutex.IsLocked(); }
private:
    Mutex&   m_mutex;
};

Normal use of this thing would look like this:
{
    AutoLock lock(m_mutex);
    // my protected code here
}

But with a simple preprocessor trick you can make the syntax identical to C#:
#define lock(x) if (!(AutoLock _l = x)); else

In other words: C# is equivalent to Playmobile™, and C++ is equivalent to LEGO™.

Sander Stoks – Last edit: 31 Jan 2007