如何在满足给定条件的情况下终止Python中的多进程?

2022-04-10 00:00:00 python python-multiprocessing

问题描述

假设我有以下函数:

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

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

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


解决方案

您可以在multiprocessing中使用eventterminate,因为您要在其中一个子进程中满足条件后停止所有进程。

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

一旦某个进程将x的值设置为5,则事件即被设置。

Eventsetunset持续签入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)Python27python.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..

相关文章