title: Using fetch-and-add as lock
body: <p>I am trying to understand how fetch-and-add can be used as a lock. Here is what the book (OS's: 3 Easy pieces) says: </p>
  
  <blockquote>
    <p>The basic operation is pretty simple: when
    a thread wishes to acquire a lock, it first does an atomic fetch-and-add
    on the ticket value; that value is now considered this thread’s “turn”
    (myturn). The globally shared lock->turn is then used to determine
    which thread’s turn it is; when (myturn == turn) for a given thread,
    it is that thread’s turn to enter the critical section.</p>
  </blockquote>
  
  <p>What I do not understand is how the thread checks if the lock held by another process before entering the cretical seection. All I can read that the value will be incremented, no mention of checks! </p>
  
  <p>Another part says:</p>
  
  <blockquote>
    <p>Unlock is accomplished
    simply by incrementing the turn such that the next waiting thread (if
    there is one) can now enter the critical section.</p>
  </blockquote>
  
  <p>Which I can not interpret in a way where checks will not be performed, which can not be true becuase it compremises the whole porpose of locking cretical sections. What am I fmissing here? Thanks.</p>