title: The right way to limit maximum number of threads running at once?
body: <p>I'd like to create a program that runs multiple light threads, but limits itself to a constant, predefined number of concurrent running tasks, like this (but with no risk of race condition):</p>
  
  <pre><code>import threading
  
  def f(arg):
      global running
      running += 1
      print("Spawned a thread. running=%s, arg=%s" % (running, arg))
      for i in range(100000):
          pass
      running -= 1
      print("Done")
  
  running = 0
  while True:
      if running &lt; 8:
          arg = get_task()
          threading.Thread(target=f, args=[arg]).start()
  </code></pre>
  
  <p>What's the safest/fastest way to implement this?</p>