首页 > 解决方案 > 在同时运行的两个函数中访问同一对象的属性

问题描述

您好,我遇到了一个奇怪的问题,也许有人可以提供帮助,我首先使用相同的参数运行 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(),传感器的数据属性内部的值属性被更新。

但在第二个函数中,iotDevice.connectedSensors[0].data.valueis 始终等于零。我觉得这种行为很奇怪,因为这是同一个对象。此外,如果我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()

标签: pythonobjectmultiprocessingvisibility

解决方案


看到这个答案。本质上,发生的事情是您的数据在被发送到流程以完成工作之前被“腌制”。收到物品后,将其拆包。因此,对象被克隆多于传递。因此,您实际上正在使用 的两个单独副本iotComponent,这就解释了为什么即使您“知道”工作正在完成,您实际上也看不到其中发生任何更改。鉴于此,可能有一种方法可以做到这一点。但是,最好不要使用Process,而是使用Thread,请参阅此处。不同之处在于,根据this,线程更适合 I/O-bound 操作,您的传感器当然是这样。


推荐阅读