如何在满足给定条件时在python中终止多进程?

时间:2017-12-20 10:24:29

标签: python python-multiprocessing

假设我有这个功能:

def f():  
    while True:          
        x = generate_something()  
        if x == condition:  
            return x

if __name__ == '__main__':
    p=Pool(4)

我想在多进程中运行此函数,当其中一个进程满足我的函数条件时,我希望所有其他进程停止。

1 个答案:

答案 0 :(得分:1)

您可以在event中使用terminatemultiprocessing,因为您希望在其中一个子流程中遇到条件后停止所有流程。

检查下面的工作示例,其中我创建了两个进程,它将检查变量x的值是否为5。

一旦其中一个流程将x的值设置为5,就会设置事件。

Event setunset会在main代码中不断检查。

<强>代码:

import random
import multiprocessing
import sys
import time

def generate_something():
    return random.choice(range(10))

def f(event):
    while True:
        x = generate_something()
        print "Value is ",x
        if x == 5:
            print "Got what I am searching for."
            event.set()
        time.sleep(2)

if __name__ == '__main__':

    jobs = []
    #Create Event
    event = multiprocessing.Event()

    #Create two processes
    for i in range(2):
        p = multiprocessing.Process(target=f,args=(event,))
        p.start()
        jobs.append(p)

    #Check whether event is set or not
    #When set close all child processes
    while True:
        if event.is_set():
            print "Exiting all child processess.."
            for i in jobs:
                #Terminate each process
                i.terminate()
            #Terminating main process
            sys.exit(1)
        time.sleep(2)

<强>输出:

"C:\Program Files (x86)\Python27\python.exe" C:/Users/punddin/PycharmProjects/demo/a.py
Value is  4
Value is  2
Value is  7
Value is  6
Value is  3
Value is  4
Value is  8
Value is  3
Value is  8
Value is  1
Value is  9
Value is  9
Value is  1
Value is  6
Value is  5
Got what I am searching for.
Value is  6
Exiting all processess..