Skip to main content
 首页 » 编程设计

python之作为 multiprocessing.Process 目标的对象方法

2025年05月04日7wayfarer

我正在修补线程,有人可以阐明这里发生了什么吗?

from multiprocessing import Process 
from time import sleep 
 
class Thing(object): 
    def __init__(self): 
        print "__init__:", id(self) 
        self.a = 100 
        self.b = 200 
 
  def run(self): 
      while True: 
          sleep(5) 
          print id(self.a), self.a, '*', id(self.b), self.b 

然后我通过 python -i 打开这个脚本并执行:

t = Thing() 
p = Process(target=t.run) 
p.start() 
# Thread starts running and reporting IDs every 5 seconds 
 
# if I do.. 
t.a = 500 
 
# The address of `t.a` changes (using `id()`) and the thread still reports 100. 

我知道期望它工作意味着一些非常粗略的线程通信,但看起来在某些时候有两个 Thing() 对象,一个对我可用,另一个在 Process() 中。它什么时候被复制?

最重要的是:

如何更改 Process() 中 self.a 的值?

请您参考如下方法:

在这种情况下,您使用的是进程而不是线程,因此您需要进程间通信。你可以用队列来实现。参见 http://docs.python.org/dev/library/multiprocessing.html ,寻找 17.2.1.3。在进程之间交换对象。