title: Thread starvation while locking in a loop in Python
body: <p>I have an application which is acquiring a lock in a loop in one thread to
  perform some task. There's also a second thread that also wants to acquire the lock from
  time to time. The problem is, this second thread barely even gets the chance to
  perform it's work, as the first one almost always locks first. I hope the
  following code will clarify what I'm trying to say:</p>
  
  <pre><code>import time
  from threading import Lock, Thread
  
  lock = Lock()
  
  
  def loop():
      while True:
          with lock:
              time.sleep(0.1)
  
  thread = Thread(target=loop)
  thread.start()
  
  before = time.time()
  lock.acquire()
  print('Took {}'.format(time.time() - before))
  </code></pre>
  
  <p>If the application gets to <code>print</code> you'll notice that it needed way more than
  just 0.1s. But sometimes it also happens that it just waits indefinitely. I've tested this both in Python 2.7.11 and Python 3.4.3 on Debian Linux 8 and it works identically.</p>
  
  <p>This behaviour is counter-intuitive for me. After all when the lock is released
  in <code>loop</code>, the <code>lock.acquire</code> was already waiting for its release and it should
  immediately acquire the lock. But instead it looks like the loop gets to acquire
  the lock first, even though it wasn't waiting for its release at all at the
  release moment.</p>
  
  <p>The solution I've found is to sleep between each loop iteration in unlocked state, but that
  doesn't strike me as an elegant solution, neither does it explain to me what's
  happening. </p>
  
  <p>What am I missing?</p>