该屏障设置一个线程计数,这些线程将一起等待,直到达到该计数为止。在测试中有一点变化
import time
import random
import threading
def f(b):
time.sleep(random.randint(2, 10))
print("{} woke at: {}".format(threading.current_thread().getName(), time.ctime()))
b.wait()
print("{} passed the barrier at: {}".format(threading.current_thread().getName(), time.ctime()))
barrier = threading.Barrier(3)
for i in range(3):
t = threading.Thread(target=f, args=(barrier,))
t.start()
您可以看到所有线程在不同的时间从睡眠中唤醒,但从
wait
同时。
$ python3 o.py
Thread-2 woke at: Sun May 20 11:59:16 2018
Thread-3 woke at: Sun May 20 11:59:21 2018
Thread-1 woke at: Sun May 20 11:59:22 2018
Thread-1 passed the barrier at: Sun May 20 11:59:22 2018
Thread-2 passed the barrier at: Sun May 20 11:59:22 2018
Thread-3 passed the barrier at: Sun May 20 11:59:22 2018