【问题标题】:Stopping the processes spawned using pool.apply_async() before their completion在完成之前停止使用 pool.apply_async() 生成的进程
【发布时间】:2016-01-24 18:39:00
【问题描述】:

假设我们有一些使用 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


    【解决方案1】:

    我从来没有这样做过,但是 python 文档似乎给出了一个关于如何做到这一点的想法。

    参考:https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate

    在你的 sn-p 中,我会这样做:

    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(),然后显示减法,因为我已经习惯了。

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      相关资源
      最近更新 更多