title: Pausing two Python threads while a third one does stuff (with locks?)
body: <p>I'm new to concurrent programming.</p>
  
  <p>I'd like to execute three tasks repeatedly. The first two should run all the time, the third should run every hour or so. The first two tasks can run in parallel, but I always want to pause them while the third task is running.</p>
  
  <p>Here's the skeleton of what I've tried:</p>
  
  <pre><code>import threading
  import time
  
  flock = threading.Lock()
  glock = threading.Lock()
  
  def f():
      while True:
          with flock:
              print 'f'
              time.sleep(1)
  
  def g():
      while True:
          with glock:
              print 'g'
              time.sleep(1)
  
  def h():
      while True:
          with flock:
              with glock:
                  print 'h'
          time.sleep(5)
  
  threading.Thread(target=f).start()
  threading.Thread(target=g).start()
  threading.Thread(target=h).start()
  </code></pre>
  
  <p>I would expect this code to print an f and a g every second, and an h about every five seconds. However, when I run it it takes around 12 f's and 12 g's before I start seeing some h's. It's looks like the first two threads constantly release and re-acquire their locks while the third thread is left out of the loop.</p>
  
  <ol>
  <li>Why is that? When the third thread tries to acquire a currently held lock, and it is then released, shouldn't acquisition immediately succeed instead of the first/second thread immediately acquiring it again? I am probably misunderstanding something.</li>
  <li>What would be a good way to achieve what I want?</li>
  </ol>
  
  <p>Note: moving the <code>time.sleep(1)</code> calls out of the with flock/glock block works for this simple example, but apparently not for my real application where the threads spend most of their time doing the actual operations. When the first two threads sleep for a second after each execution of the loop body, with the lock released, the third task still never gets executed.</p>