我有4个共享变量。我正根据正在运行的进程更新一对。以下是代码。
class App(multiprocessing.Process):
def __init__ (self,process_id):
multiprocessing.Process.__init__(self)
self.process_id = process_id
def run(self,X,Y,lock):
while True:
with lock :
#some calculations which returns x and y
print 'x and y returned are :',x,y
try:
X.value = x
Y.value = y
except Exception ,e:
print e
if __name__ == '__main__':
xL = Value('d',0.0)
xR = Value('d',0.0)
yL = Value('d',0.0)
yR = Value('d',0.0)
lock = Lock()
a = A('1')
b = B('2')
process_a = Process(target = a.run, args(xL,yL,lock, ))
process_b = Process(target = b.run, args(xR,yR,lock, ))
process_a.start()
process_b.start()
这是输出:
返回的x和y是:375 402
'float'对象没有属性'value'
任何帮助。 ?
答案 0 :(得分:4)
看一下代码的三个部分,我在括号中用数字注释:
def run(self,X,Y,lock):
while True:
#some calculations which returns x and y
with lock :
X.value = x
Y.value = y
# (3) you now try to access an attribute of the arguments
# called 'value'
print X.value , Y.value , self.process_id
if __name__ == '__main__':
xL = Value('d',0.0) # (1) these variables are assigned some objects that
xR = Value('d',0.0) # are returned by the function 'Value'
yL = Value('d',0.0)
yR = Value('d',0.0)
lock = Lock()
a = A('1')
b = B('2')
# (2) now your variables are being passed to the 'a.run' and 'b.run'
# methods
process_a = Process(target = a.run, args(xL,yL,lock, ))
process_b = Process(target = b.run, args(xR,yR,lock, ))
process_a.start()
process_b.start()
当您跟踪代码的执行时,您可以看到它正在尝试访问函数value
返回的任何对象中名为Value
的属性。您的错误消息告诉您Value
正在返回float
个对象,这些对象没有value
属性。
以下情况之一(很可能)对您不利:
Value
没有按照你的想法行事,并且当它不应该返回浮动时。