为什么 Process 对象的属性在 运行 之后不保留?
Why are attributes of a Process object not kept after run?
我有以下 Process
的子类:
from multiprocessing import Process
class MyProcess(Process):
def __init__(self, **kwargs):
self.my_attribute = "debug0"
print("my_attribute : ", self.my_attribute)
super().__init__(**kwargs)
self.my_attribute = "debug1"
print("my_attribute : ", self.my_attribute)
def run(self):
self.my_attribute = "debug2"
print("my_attribute : ", self.my_attribute)
my_process = MyProcess()
my_process.start()
my_process.join()
print("my_process.my_attribute : ", my_process.my_attribute)
我得到以下日志:
my_attribute : debug0
my_attribute : debug1
my_attribute : debug2
my_process.my_attribute : debug1
为什么属性 my_attribute
在 run
期间被更改时没有保持在 run
方法中的设置?在 run
函数完成执行后,如何在这种情况下设置一个保持其值的属性?
运行 函数 运行 在一个单独的进程中,有自己的内存 space 和自己的 my_process
对象副本,所以它不能直接影响父进程中的my_process
对象。如果您希望在子进程中的 运行 函数 运行 发生变化时父进程发生某些变化,则必须安排某种进程间通信。这不会因为使用 Process
class.
而自动发生
我有以下 Process
的子类:
from multiprocessing import Process
class MyProcess(Process):
def __init__(self, **kwargs):
self.my_attribute = "debug0"
print("my_attribute : ", self.my_attribute)
super().__init__(**kwargs)
self.my_attribute = "debug1"
print("my_attribute : ", self.my_attribute)
def run(self):
self.my_attribute = "debug2"
print("my_attribute : ", self.my_attribute)
my_process = MyProcess()
my_process.start()
my_process.join()
print("my_process.my_attribute : ", my_process.my_attribute)
我得到以下日志:
my_attribute : debug0
my_attribute : debug1
my_attribute : debug2
my_process.my_attribute : debug1
为什么属性 my_attribute
在 run
期间被更改时没有保持在 run
方法中的设置?在 run
函数完成执行后,如何在这种情况下设置一个保持其值的属性?
运行 函数 运行 在一个单独的进程中,有自己的内存 space 和自己的 my_process
对象副本,所以它不能直接影响父进程中的my_process
对象。如果您希望在子进程中的 运行 函数 运行 发生变化时父进程发生某些变化,则必须安排某种进程间通信。这不会因为使用 Process
class.