【发布时间】:2017-12-22 10:58:59
【问题描述】:
我在这段代码中遇到了奇怪的 python 行为:
#!/usr/bin/python
import multiprocessing
import time
import sys
class worker(multiprocessing.Process):
def __init__(self, val):
super(worker,self).__init__()
self.val = val
def update_val(self,val):
self.val = val
print("self.val now is %s" %(self.val))
def run(self):
while True:
print("Worker report: val is %s" % (self.val))
time.sleep(self.val)
subproc = worker(10)
subproc.start()
while True:
new_val = sys.stdin.readline().rstrip()
if new_val:
subproc.update_val(new_val)
print("Main report: val is %s" % (subproc.val))
我希望,对象subproc 中的变量val 被update_val 函数更改。
但我很惊讶,因为该变量仅针对来自main 进程的查询进行了更改。
函数run 仍然使用旧值:
$ ./test.py
Worker report: val is 10
Worker report: val is 10
5
self.val now is 5
Main report: val is 5
Main report: val is 5
Worker report: val is 10
Worker report: val is 10
问题可能是什么原因?此代码在 Python2.7 和 Python3.6 中的工作方式类似。提前致谢!
【问题讨论】:
标签: python class python-multiprocessing