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
You can compare this to the difference between Playmobile and LEGO. If you overhear an argument between two kids over which is "best", the reasoning is often something like this:
"My Playmobile castle is much nicer than your LEGO castle. Look, if I fire a cannon ball against this spot in the wall, a very realistic hole appears!"
"And if I hit it at some other spot?"
"Well, then nothing happens. But as long as you aim at exactly the right spot, it's really cool. Also, my Playmobile ship looks much more realistic than your LEGO ship. It's made from one piece, and it has much smoother curves. Look at all those silly studs on all edges of your ship. Real ships don't have that."
"But I can take my ship and rebuild it into an airplane."
"Why would you want to do that?"
You can decide for yourself which you like better, but I feel that C# is equivalent to Playmobile™, and C++ is equivalent to LEGO™.
By the way: my introductionary computer programming book is available here.