The right way to limit maximum number of threads running at once?
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): 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 < 8: arg = get_task() threading.Thread(target=f, args=[arg]).start() What's the safest/fastest way to implement this? It sounds like you want to implement the producer/consumer pattern with eight