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

2024-09-30 20:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

你好我有个奇怪的问题也许有人能帮上忙, 我首先用同一个参数运行两个不同的函数,这是一个已经实例化的对象:

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()

Tags: 函数selftargetdatavalueargssensorstart
1条回答
网友
1楼 · 发布于 2024-09-30 20:35:29

this答案。从本质上讲,您的数据在被发送到进程以完成工作之前是“pickle”的。当收到这些物品时,它们就被打开了。因此,对象的克隆比传递更多。因此,实际上您使用的是iotComponent的两个独立副本,这就解释了为什么即使您“知道”工作正在进行,也无法看到其中一个副本上发生的任何更改。如果this,可能有办法做到这一点。但是,最好不要使用Process,而是使用Thread,请参见here。不同之处在于,根据this,线程更适合于I/O绑定的操作,而您的传感器肯定是这样的

相关问题 更多 >