满足条件时终止多处理进程

我试图运行的想法是这样的:


运行 3 个进程进行计算一旦 3 个进程之一完成任务立即杀死其他进程并继续执行主要任务,我不能让它再运行了


我尝试过的事情是:通过 multiprocessing.manager 放置全局变量,但这仍然让进程完成它们的循环。引发异常


操作系统:Windows 蟒蛇:2.7


def f(name):

    Doing = True

    try:

        while Doing:

            print 'DOING',name

            somecodethatmarksDoingAsFalse()

    except Exception as error:

        print 'bye'

        print error

        Doing = False

        return True





if __name__ == '__main__':

    p = multiprocessing.Process(target=f, args=('bob',))

    p2 = multiprocessing.Process(target=f, args=('tom',))

    p.start()

    p2.start()


    p.join()

    p2.join()



    raise Exception('I know Python!')

    sys.exit()

我希望能够在将执行标记为 false、引发异常或在对其中一个进程进行计算时以任何方式终止所有进程


编辑:它不是重复的,因为它仍然完成执行代码,例如请求模块仍然发送数据


湖上湖
浏览 163回答 1
1回答

千万里不及你

如果您需要立即杀死,您可以使用 amultiprocessing.Event通知父进程满足条件并让它立即杀死工作进程。管理器进程对于这种需要的少量同步来说太重了。import osfrom datetime import datetimefrom multiprocessing import Process, Eventdef worker(range_, target, found_event):&nbsp; &nbsp; print('{} | pid: {} started'.format(datetime.now(), os.getpid()))&nbsp; &nbsp; for x in range_:&nbsp; &nbsp; &nbsp; &nbsp; if x == target:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('{} | pid: {} found target'.format(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; datetime.now(), os.getpid())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; found_event.set()if __name__ == "__main__":&nbsp; &nbsp; N_WORKERS = 4&nbsp; &nbsp; step = int(200e6)&nbsp; &nbsp; ranges = [range(x, x + step) # change `range` to `xrange` for Python 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for x in range(0, N_WORKERS * step, step)]&nbsp; &nbsp; # range(0, 200000000), ..., range(800000000, 1000000000)]&nbsp; &nbsp; target = int(150e6)&nbsp; # <-- worker finding this value triggers massacre&nbsp; &nbsp; found_event = Event()&nbsp; &nbsp; pool = [Process(target=worker, args=(range_, target, found_event))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for range_ in ranges]&nbsp; &nbsp; for p in pool:&nbsp; &nbsp; &nbsp; &nbsp; p.start()&nbsp; &nbsp; found_event.wait()&nbsp; # <- blocks until condition met&nbsp; &nbsp; print('{} | terminating processes'.format(datetime.now()))&nbsp; &nbsp; for p in pool:&nbsp; &nbsp; &nbsp; &nbsp; p.terminate()&nbsp; &nbsp; for p in pool:&nbsp; &nbsp; &nbsp; &nbsp; p.join()&nbsp; &nbsp; print('{} | all processes joined'.format(datetime.now()))示例输出:2019-01-17 01:55:33.781884 | pid: 28376 started2019-01-17 01:55:33.782333 | pid: 28377 started2019-01-17 01:55:33.782851 | pid: 28378 started2019-01-17 01:55:33.783484 | pid: 28379 started2019-01-17 01:55:54.715425 | pid: 28376 found target2019-01-17 01:55:54.715613 | terminating processes2019-01-17 01:55:54.716326 | all processes joinedProcess finished with exit code 0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python