gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:21:37 25 4
gpt4 key购买 nike

假设我有这个功能:

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

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

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

最佳答案

您可以在多处理中使用事件终止,因为您希望在子进程之一满足条件后停止所有进程。

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

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

Event 是否已setunsetmain 代码中持续检查。

代码:

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..

关于python - 如何在满足给定条件时终止Python中的多进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com