在java的java.util.concurrent工具类有闭锁的一个灵活的实现CountDownLatch
在Python中我们可以借助 threading 库中的Condition来实现CountDownLatch
python 版本的CountDownLatch
from threading import Condition
class CountDownLatch:
def __init__(self, count):
self.count = count
self.condition = Condition()
def await(self):
self.condition.acquire()
try:
while self.count > 0:
self.condition.wait()
finally:
self.condition.release()
def count_down(self):
self.condition.acquire()
self.count -= 1
if self.count <= 0:
self.condition.notifyAll()
self.condition.release()