在同时运行的两个函数中访问同一对象的属性

时间:2018-09-27 18:24:02

标签: python object multiprocessing visibility

你好,我遇到一个奇怪的问题,也许有人可以帮忙, 我首先使用相同的参数运行2个不同的函数,这是一个已实例化的对象:

iotComponent.connectedSensors=sensorList
iotComponent.connectedHUIs=HUIList

Coap = multiprocessing.Process(target=runCoapSync,args=(iotComponent,))
huis = multiprocessing.Process(target=runHuis,args=(iotComponent,))
huis.start()
Coap.start()

然后这是两个函数:

async def runCoap(iotDevice):

    context = await Context.create_client_context()
    sensor=iotDevice.connectedSensors[0]
    while True:
        await asyncio.sleep(1)
        sensor.sense()
        lightMsg = iotDevice.applicationInterface.createMsg( sensor, iotDevice.communicationProtocol.name)
        await iotDevice.communicationProtocol.sendMsg(context,lightMsg,"light")


def runHuis(iotDevice):
    print("----------------1---------------")
    LCD=iotDevice.connectedHUIs[0]
    while True:
        LCD.alertHuman(iotDevice.connectedSensors[0].data.value)

在调用sensor.sense()的第一个函数中,传感器的data属性内的value属性被更新。

但是在第二个函数中,iotDevice.connectedSensors[0].data.value始终等于零。我发现此行为很奇怪,因为这是同一对象。此外,如果我在第二个函数中添加一行sensor.sense(),则该值会更新,但与第一个函数中打印的值不同。

编辑0: 这是sense()方法:

 def sense(self):
        pinMode(self.pinNumber, "INPUT")
        lightSensorValue = analogRead(self.pinNumber)
        self.data.timestamp=str(round(time.time(), 3))
        self.data.value=lightSensorValue

如果有人提出这个想法,那将是很棒的!

解决方案:正如我接受的答案中所说的那样,我尝试使用线程,它的工作原理就像一个魅力:

Coap = threading.Thread(target=runCoapSync,args=(iotComponent,))
huis = threading.Thread(target=runHuis,args=(iotComponent,))
huis.start()
Coap.start()

1 个答案:

答案 0 :(得分:1)

请参见this答案。从本质上讲,正在发生的事情是在将数据发送到流程以完成工作之前先对其进行“腌制”。收到对象后,将它们拆包。因此,对象的克隆比传递的要多。因此,您实际上正在使用iotComponent的两个单独的副本,这说明了即使您“知道”工作已经完成,为什么实际上看不到任何变化。给定this,也许有一种方法可以做到这一点。但是,最好不要使用Process,而应使用Thread,请参阅here。区别在于,根据this,线程对于I / O绑定操作更好,而传感器肯定是这样。