我正在修补线程,有人可以阐明这里发生了什么吗?
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。在进程之间交换对象。
关于python - 作为 multiprocessing.Process 目标的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18272345/