title: Implementation of a lock using test and set
body: <p>Below is the code is given in <a href="http://pages.cs.wisc.edu/~remzi/OSTEP/" rel="nofollow noreferrer">OSTEP book</a> regarding the implementation of a lock using test and set instruction. My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?</p>
  
  <pre><code>typedef struct __lock_t {
   int flag;
   } lock_t;
  
   void init(lock_t *lock) {
   // 0 indicates that lock is available, 1 that it is held
   lock-&gt;flag = 0;
   }
  
   void lock(lock_t *lock) {
   while (TestAndSet(&amp;lock-&gt;flag, 1) == 1)
   ; // spin-wait (do nothing)
   }
  
   void unlock(lock_t *lock) {
   lock-&gt;flag = 0;
   }
  </code></pre>