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

标签 python multiprocessing

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

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/

相关文章:

python - 使用 Playwright 保存登录信息

python - SymPy 无法求解三角方程组

python - 在多处理中处理大量数据和进程

python : Process calling GRPC server gets stuck and terminates unexpectedly

python - 使用多处理迭代幂集

Python pytz : non-existent time gets AmbiguousTimeError, 不是 NonExistentTimeError

python - 如何为 python 字典中的键设置多个值?

python - Django floppyforms OSMPointWidget 不显示 map

python - 在基于fork的多重处理期间,如何防止python记录器和处理程序的继承?

multithreading - 使用 openMP 进行多核处理与多线程