[英]Stopping the processes spawned using pool.apply_async() before their completion
Suppose we have some processes spawned using pool.apply_async(). 假设我们使用pool.apply_async()生成了一些进程。 How can one stop all other processes when either one of them returns a value?
当一个进程返回值时,该如何停止所有其他进程? Also, Is this the right way to get running time of an algorithm?
另外,这是获取算法运行时间的正确方法吗? Here's the sample code :-
这是示例代码:-
import timeit
import multiprocessing as mp
data = range(1,200000)
def func(search):
for val in data:
if val >= search:
# Doing something such that other processes stop ????
return val*val
if __name__ == "__main__":
cpu_count = mp.cpu_count()
pool = mp.Pool(processes = cpu_count)
output = []
start = timeit.default_timer()
results = []
while cpu_count >= 1:
results.append(pool.apply_async(func, (150000,)))
cpu_count = cpu_count - 1
output = [p.get() for p in results]
stop = timeit.default_timer()
print output
pool.close()
pool.join()
print "Running Time : " + str(stop - start) + " seconds"
I've never done this, but python docs seems to give an idea about how this should be done. 我从来没有做过,但是python文档似乎给了一个应该怎么做的想法。
Refer: https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate 请参阅: https : //docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate
In your snippet, I would do this: 在您的代码段中,我将执行以下操作:
while cpu_count >= 1:
if len(results)>0:
pool.terminate()
pool.close()
break
results.append(pool.apply_async(func, (150000,)))
cpu_count = cpu_count - 1
Also your timing method seems okay. 而且您的计时方法似乎还可以。 I would use
time.time()
at start and stop and then show the subtraction because I'm used to that. 我会在开始和停止时使用
time.time()
,然后显示减法,因为我已经习惯了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.