我在这里有一个非常缓慢和随机的功能。
我只想要foo()的第一个结果。
from random import randint
def foo(i): # Generating random number in a very slow way
y = randint(1,1000000)
while y != randint(1,1000000):
pass
return y
我想提高速度,所以我创建了几个进程, 但它减慢了我的速度,给了我不必要的结果。
from multiprocessing import Pool
with Pool(processes = 8) as pool:
result = pool.map(foo, [i for i in range(8)])
# A lot of time passed
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]
那么,无论如何终止chunked函数中的其他子进程并返回结果就像这样?
from random import randint
def foo(i): # Generating random number in a very slow way
y = randint(1,1000000)
while True:
x = randint(1,1000000)
if x == y:
pool.terminateAllOtherSubprocesses()
return y
from multiprocessing import Pool
with Pool(processes = 8) as pool:
result = pool.barFunc(foo, [i for i in range(8)])
# Less than a second passed
>>> result
[42]