[英]Stopping the processes spawned using pool.apply_async() before their completion
假設我們使用pool.apply_async()生成了一些進程。 當一個進程返回值時,該如何停止所有其他進程? 另外,這是獲取算法運行時間的正確方法嗎? 這是示例代碼:-
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"
我從來沒有做過,但是python文檔似乎給了一個應該怎么做的想法。
請參閱: https : //docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate
在您的代碼段中,我將執行以下操作:
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
而且您的計時方法似乎還可以。 我會在開始和停止時使用time.time()
,然后顯示減法,因為我已經習慣了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.