python - 使用哪种机制来正确释放多个线程获取的资源

标签 python multithreading

假设我有下面介绍的两个函数。第一个 (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/

相关文章:

python - pandas .iloc 和 .iat 之间的区别?

iPhone Gameloop 从单独的线程渲染更新

c++ - pthread_yield 不能在线程之间正确循环

c - C : How can I stop the threads from interfering with each other? 中的多线程

java - 打印GCApplicationStoppedTime

python - 如何从 Odoo 10 中的自定义模块修改 noupdate ="1"XML 记录?

python - python 是否足够聪明,可以用常量结果替换函数调用?

java - 动态显示附加文本的 TextArea

c++ - 通过 Boost.Python 将 C 风格的数组数据成员暴露给 Python

python 谷歌应用程序引擎编程