[英]How can I make sure that two function calls are always made consecutively with multiple threads in Python?
I'm using Pathos like this: 我这样使用Pathos:
from pathos.multiprocessing import ProcessingPool as Pool
def foo(bar):
fn1(bar)
fn2(bar)
Pool().map(foo, data)
I want fn1
and fn2
to be executed as one atomic operation such that no threads can produce function calls in a sequence like fn1, fn1, fn2, fn2
. 我希望将fn1
和fn2
作为一个原子操作执行,以使没有线程可以按fn1, fn1, fn2, fn2
类的顺序生成函数调用。
You need to use a lock like it is described in the 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])
But, why are you using multiprocessing if you don't want to call your function in parallel? 但是,如果不想并行调用函数,为什么还要使用多处理?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.