从multiprocessing.Process继承的Python类的设置值问题 [英] Issue with setting value for Python class inherited from multiprocessing.Process
问题描述
为什么要输入这个代码
import multiprocessing
import time
class Bot(multiprocessing.Process):
def __init__(self):
self.val = 0
multiprocessing.Process.__init__(self)
def setVal(self):
self.val = 99
def run(self):
while True:
print 'IN: ', self.val
time.sleep(2)
if __name__ == '__main__':
bot = Bot()
bot.start()
bot.setVal()
while True:
print 'OUT: ', bot.val
time.sleep(2)
给出以下输出?
OUT: 99
IN: 0
OUT: 99
IN: 0
OUT: 99
IN: 0
OUT: 99
IN: 0
OUT: 99
IN: 0
OUT: 99
IN: 0
...
您可能会猜到,我希望获得全部99个输入和输出.但我不.为什么?我想念什么?
As you may guess i expect to get all 99, IN and OUT. But i do not. Why? What am i missing?
推荐答案
问题是,一旦启动第二个过程,就从两个不同的过程进行打印.
The problem is that once you start the second process, you are printing from 2 different processes.
父进程具有bot的原始实例,然后将该值设置为99.父进程正在打印OUT,这就是为什么要打印99的原因.
The parent process has the original instance of bot, with the value then set to 99. The parent process is printing OUT which is why you get the value 99 printed.
(新)子进程以从机器人对象复制的状态开始,就像您调用多处理方法start()
时的状态一样.因此,它的状态为0.您永远不会在子进程中调用setVal,因此它的值保持为0,并且IN打印print 0.
The (new) subprocess starts with state copied from the bot object as it was when you called the multiprocessing method start()
. Because of this, it has a state of 0. You never call setVal in the subprocess and so it's value remains 0, and the IN prints print 0.
如果要在父流程和子流程之间共享这样的状态信息,请阅读以下内容: http://docs.python.org/2/library /multiprocessing.html#sharing-state-between-processes
If you want to share state information like this between the parent process and the subprocess, have a read of this: http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes
这篇关于从multiprocessing.Process继承的Python类的设置值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!