假設我有兩個函數如下所示。第一個(use_stuff
)可以被許多線程用來做一些計算,而第二個(clean_stuff_cache
)可以偶爾在單獨的線程中調用,當我們需要更新緩存時。我應該使用哪種同步機制(我稱之爲counter
)來確保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]
你可以試試信號,當線程要刷新等等緩存,發送信號給其他線程,這樣他們可以退出/ sotp /暫停,清理緩存後,只需發送另一個信號重新啓動 – Raskayu