我正在用python编写一些涉及多处理的代码。代码是这样的:
from multiprocessing import Pool
global stop
stop = False
def somefunction():
#Perform some action and then set variable stop to True which takes around 5-7 mins
stop = True
if __name__ == '__main__':
p = Process(target= somefunction)
p.start()
while(stop == False):
#some other action解释上述代码:
我需要运行while循环,直到停止变量值变为真为止。
在大约5-7分钟内,在somefunction()方法中执行其他一些计算之后,该值将变为True。在启动while循环之前由进程触发的某个函数()。
这里的问题是,即使使用多进程将变量设置为True,但while循环仍在运行。我将变量声明为全局变量,以使其在所有方法中都可访问。
它仍然不起作用。
有人能告诉我我在这里做错了什么吗。
非常感谢YOur的帮助。谢谢。
发布于 2022-05-18 10:21:01
当使用多处理时,进程正在生成一个全新的python实例。因此,子进程中的变量将不同于父进程中的同名变量。(或任何其他子进程)
这里最好的解决方案是使用共享内存变量,就像您在文档上看到的那样
发布于 2022-05-19 13:31:17
我只需使用传递给子进程的multiprocessing.Event实例,如下所示:
import time
def somefunction(stop):
#Perform some action and then set Event variable stop, which takes around 5-7 mins
time.sleep(5) # Just 5 seconds for demo purposes
stop.set()
def do_something_else():
print('Doing something else.')
time.sleep(1)
if __name__ == '__main__':
from multiprocessing import Process, Event
stop = Event()
p = Process(target=somefunction, args=(stop,))
p.start()
while(not stop.is_set()):
do_something_else()
p.join() # Wait for process to end指纹:
Doing something else.
Doing something else.
Doing something else.
Doing something else.
Doing something else.但是,更简单的是测试子进程是否仍在运行,如果我们假设它在某个时间点终止,那么它本来可以设置stop事件:
import time
def somefunction():
#Perform some action, which takes around 5-7 mins, and then terminate
time.sleep(5) # Just 5 seconds for demo purposes
def do_something_else():
print('Doing something else.')
time.sleep(1)
if __name__ == '__main__':
from multiprocessing import Process
p = Process(target=somefunction)
p.start()
while(p.is_alive()):
do_something_else()
p.join() # Wait for process to endhttps://stackoverflow.com/questions/72287151
复制相似问题