gpt4 book ai didi

python多处理成员变量未设置

转载 作者:行者123 更新时间:2023-11-30 23:59:02 26 4
gpt4 key购买 nike

在下面的脚本中,我得到“收到停止消息”输出,但该过程永远不会结束。这是为什么?除了终止或 os.kill 之外,还有其他方法可以结束进程吗?

from multiprocessing import Process
from time import sleep

class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = False

def run(self):
while self.stop == False:
print "running"
sleep(1.0)

def end(self):
print "stop message received"
self.stop = True

if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()

最佳答案

start 方法已将对象克隆到一个单独的进程中,并在其中执行 runend 方法没有什么特别的,因此它在调用它的进程中运行——它对该对象执行的更改不会发送到克隆对象。

因此,请使用适当的进程间通信方式,例如 multiprocessing.Event实例,例如:

from multiprocessing import Process, Event
from time import sleep

class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = Event()

def run(self):
while not self.stop.is_set():
print "running"
sleep(1.0)

def end(self):
print "stop message received"
self.stop.set()

if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()

如您所见,所需的更改很少。

关于python多处理成员变量未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2685845/

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