如何确保在 Python 中的多个线程始终连续进行两个函数调用?

How can I make sure that two function calls are always made consecutively with multiple threads in Python?

我正在这样使用 Pathos:

from pathos.multiprocessing import ProcessingPool as Pool
def foo(bar):
   fn1(bar)
   fn2(bar)

Pool().map(foo, data)

我希望 fn1fn2 作为一个原子操作执行,这样就没有线程可以像 fn1, fn1, fn2, fn2 这样的顺序产生函数调用。

您需要像 documentation 中描述的那样使用锁。

def foo(lock, bar):
    lock.acquire()
    try:
       fn1(bar)
       fn2(bar)
    finally:
        lock.release()

if __name__ == '__main__':
    lock = Lock()
    Pool().map(foo, [(l, d) for d in data])

但是,如果您不想并行调用您的函数,为什么要使用多处理?