import threading, time, sys
sem = threading.Semaphore(3)
def foobar(n):
with sem:
print(n, sem._value, end=" | ")
sys.stdout.flush()
time.sleep(2)
threads = []
for counter in range(20):
th = threading.Thread(target=foobar, args=(counter, ))
th.start()
threads.append(th)
for th in threads:
th.join()
Ausgabe:
0 2 | 1 1 | 2 0 | 3 0 | 4 0 | 5 0 | 7 1 | 6 0 | 8 0 |
nach 2 Sekunden
nach 2 Sekunden