title: Can I acquire 2+ locks at the same time in python
body: <p>Can I acquire 2 or more locks at the same time in python directly?</p>
  
  <pre><code>from thread import allocate_lock, start_new_thread
  
  def A_thread( A_lock ):
     while 1:
         with A_lock:
             pass # assume complex code here
  
  
  def B_thread( B_lock ):
     while 1:
         with B_lock:
             pass # assume complex code here
  
  A_lock = allocate_lock()
  B_lock = allocate_lock()
  
  A_thread = start_new_thread( A_thread, ( A_lock, ) )
  B_thread = start_new_thread( B_thread, ( B_lock, ) )
  
  while 1:
      with A_lock and B_lock:
          pass # assume complex code here
  </code></pre>
  
  <p>s.t. both A_lock and B_lock should be granted at the same time or neither of them.</p>
  
  <p>I don't want to acquire locks in the same order and acquire <code>A_lock</code> when I need only <code>B_lock</code> (i.e. in <code>def B_thread(...)</code>)</p>
  
  <p>The issue of the code above is fairness between <code>A_thread</code> and <code>B_thread</code>. Since <code>main</code> thread acquire <code>A_lock</code> first, <code>A_thread</code> has lower priority over <code>B_thread</code></p>
  
  <hr>
  
  <p>Probably, better example will be</p>
  
  <pre><code>from thread import allocate_lock, start_new_thread
  
  def A_thread( A_lock, B_lock ):
     while 1:
         with B_lock and A_lock:
             pass # assume complex code here
  
  
  
  A_lock = allocate_lock()
  B_lock = allocate_lock()
  
  A_thread = start_new_thread( A_thread, ( A_lock, B_lock ) )
  
  while 1:
      with A_lock and B_lock:
          pass # assume complex code here
  </code></pre>
  
  <p>The issue here is <code>busy waiting</code>, if both <code>main</code> and <code>A</code> thread acquire their 1st lock before one of them acquire its 2nd lock, 1st thread that acquires its 2nd lock will force the other thread to start its <code>with</code> statement from the beginning. In addition, the thread that gets 2nd lock first may run next again ( <code>thread fairness</code> issue)</p>