0
我遇到了Python的多,我无法理解的一些行为......在Python中,如果我将一个普通变量传递给一个函数并使用apply_async在多个进程中执行它,会发生什么?
例如:
from multiprocessing import Pool
import time
import sys
def f(x):
time.sleep(10)
print(x)
return x * x
def f2(x, f):
time.sleep(10)
print(x, file=f)
return x * x
if __name__ == '__main__':
p = Pool(5)
for t in range(10):
p.apply_async(f, args=(t,))
p.close()
p.join() # Here it blocks and prints the number, which is normal.
p = Pool(5)
for t in range(10):
p.apply_async(f2, args=(t, sys.stdout))
p.close()
p.join() # Here it does not block and nothing happends(no output at all)...
输出是:
3
1
0
2
4
5
9
6
7
8
我知道,我们必须使用类似共享变量传递给函数时使用多处理和apply_async
,但如果我将一个正常变量传递给apply_async
中使用的函数会发生什么?