满足条件时终止所有过程 [英] Terminate all processes when condition is met

查看:87
本文介绍了满足条件时终止所有过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用starmap运行测试功能.
当进程首先找到排列[5,2,4,3,1]时,终止所有进程的最佳/最安全方法是什么?

I am using starmap to run testing function.
Whats the best/safest way to terminate all processes when a process first finds the permutation [5,2,4,3,1]?

import multiprocessing as mp
import time

def testing(lts):
    # code ....
    start_time = time.time()
    for x in range(1,500000):
        gg = [1,2,3,4,5]
        random.shuffle(gg)
        ### if gg==[5,2,4,3,1] terminate all processes
    total_time = time.time() - start_time
    return total_time

if __name__ == '__main__':

    with mp.Pool(processes=4) as pool:
    ret = pool.starmap(testing, [(lst,) for x in range(4)])

推荐答案

我对所有这些multiprocessing内容都不是很熟悉,但是设置全局变量仅适用于线程. multiprocessing创建不同的进程,因此全局变量将被复制,并且值的更改仅在 current 进程中可见.

I'm not very familiar with all this multiprocessing stuff, but setting a global variable only works with threads. multiprocessing creates different processes, so the global variable will be duplicated and a change of value is only visible in the current process.

相反,请使用Manager,它会在进程之间创建共享对象(字典,例如列表).

Instead, use a Manager, which creates a shared object between processes (dictionary, list for instance).

也许有更简单的方法,但是我选择创建一个共享的Manager.list()对象,该对象最初是空的.

There may be simpler ways, but I chose to create a shared Manager.list() object, which is initially empty.

找到组合后,只需在列表中添加一些内容即可.在所有过程中测试列表是否为空.我已经调整了您的示例,使其按原样工作(此处不需要numpyrandom.shuffle可以正常工作.

When the combination is found, just append something to the list. Test the list for emptyness in all processes. I've adapted your example so it works as-is (no need for numpy here, random.shuffle works fine.

import multiprocessing as mp, random
import time

def testing(lst):
    # code ....

    start_time = time.time()
    for x in range(1,500000):
        gg = [1,2,3,4,5]
        random.shuffle(gg)

        if gg==[5,2,4,3,1]:
            print(gg)
            lst.append(1)  # reflected on all processes
        if lst:
            # list is no longer empty: stop
            print("stop")
            break

    total_time = time.time() - start_time
    return total_time

if __name__ == '__main__':
    manager = mp.Manager()
    lst = manager.list()

    with mp.Pool(processes=4) as pool:
       ret = pool.starmap(testing, [(lst,) for x in range(4)])

    print(ret)

执行痕迹

[5, 2, 4, 3, 1]
stop
stop
stop
stop
[0.031249523162841797, 0.015624523162841797, 0.015624523162841797, 0.015624523162841797]

我们看到,当一个过程找到解决方案"时,这四个过程就停止了.

as we see, the 4 processes have stopped, when one found the "solution".

这篇关于满足条件时终止所有过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆