title: Implementing a lock
body: <p>I'm trying to understand how locks work.</p>
  
  <p>Let's say I want to implement a really simple lock in C++</p>
  
  <pre><code>class Resource{
      public:
      bool lock();
      void unlock();
      ... methods to change/read the Resource ...
  
      private:
      bool isLocked;
  }
  </code></pre>
  
  <p>The user of the Resource calls <code>lock()</code>, and if <code>isLocked</code> is true, then <code>lock()</code> returns false, and the user of the Resource has to either wait, or do something else. If <code>isLocked</code> is false, then <code>lock()</code> sets <code>isLocked</code> to true, and returns true. Then the caller can do whatever he wants to the resource. He calls <code>unlock()</code> on the resource afterwards to set <code>isLocked</code> to false.</p>
  
  <p>However, what if two users of the resource call <code>lock()</code> at precisely the same time? Does this situation rarely happen? I think more formally, this involves making the <code>lock()</code> operation "atomic", though I'm not precisely sure what that word means.</p>