假设我有下面介绍的两个函数。第一个 (use_stuff
) 可以被多个线程使用来进行一些计算,而第二个 (clean_stuff_cache
) 可以在我们需要更新时偶尔在单独的线程中调用缓存。我应该使用哪种同步机制(我在这里称之为计数器
)来确保clean_stuff_cache
将阻塞,直到所有线程完成use_stuff
例程。
stuff_cache = dict()
counter = ????
def use_stuff(id):
counter.acquire()
if id not in stuff_cache:
stuff_cache[id] = get_stuff(id)
# do some computation using stuff
do_stuff(stuff_cache[id])
counter.release()
def clean_stuff_cache(id):
counter.wait_until_zero()
# drop all the stuff being used
del stuff[id]
最佳答案
您可以在此处将Semaphore
对象与Lock
结合使用。信号量允许有一个同步计数器,如果您尝试在它为 0 时获取 if,该计数器会阻塞。
因此,如果 counter = Semaphore(0)
和 lock = Lock()
则:
def use_stuff(id):
# Increment number of running workers if your are not cleaning the cache
with lock:
counter.release()
..... do stuff...
# decrement number of running workers
counter.acquire()
def clean_stuff():
# counter.acquire return False if there is no worker running
while True:
lock.acquire()
if counter.acquire(False):
counter.release()
lock.release()
else:
break
# delay next loop so the check is only occasional
time.sleep(.01)
# here, no worker is running and the lock prevents new worker
# from starting so you can cleanup the cache...
... do clean up
lock.release()
关于python - 使用哪种机制来正确释放多个线程获取的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906948/