我是python中多处理的新手,到目前为止我见过的所有例子都是这种(文件中有一个或多个方法,然后' main '):
from multiprocessing import Process
def f1(a):
#do something
def f2(b):
#do something
if __name__ == '__main__':
f1(a1)
p = Process(target=f2, args=(b2,))
p.start()
p.join()
如果我有一个方法,它将另一个文件中的2个函数调用为并发,如下面的行,
def function():
#do something
file2.f1(a) #first concurrent method
file2.f2(b) #second concurrent method
我该怎么办? 谁能举一个简单的例子?我试过这种方式,但它在第一次循环后再次启动所有程序:
def function():
#do something
for i in range(3):
p1 = Process(target=file2.f1, args=(a)) #first concurrent method
p2 = Process(target=file2.f2, args=(b)) #second concurrent method
p1.start()
p2.start()
p1.join()
p2.join()
答案 0 :(得分:1)
问题似乎是args varialbe定义不正确,它应该是元组而不是单个变量:
def function():
#do something
for i in range(3):
p1 = Process(target=file2.f1, args=(a, )) #first concurrent method
p2 = Process(target=file2.f2, args=(b, )) #second concurrent method
p1.start()
p2.start()
p1.join()
p2.join()
如果执行顺序灵活,您可以使用Pool类触发多个调用:
from multiprocessing.pool import Pool
pool = Pool()
pool.map_async(f1, [(arg, )] * 3)
pool.map_async(f2, [(arg, )] * 3)
pool.close()
pool.join()