Skip to main content
 首页 » 编程设计

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

2024年12月31日852php

您好,我遇到了一个奇怪的问题,也许有人可以提供帮助, 我首先使用相同的参数运行 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.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() 

请您参考如下方法:

参见 this回答。本质上发生的事情是您的数据在被发送到流程以完成工作之前被“腌制”。收到对象后,它们将被解包。因此,对象被克隆的次数多于传递的次数。因此,您实际上是在使用 iotComponent 的两个单独副本,这解释了为什么即使您“知道”工作正在完成,您实际上也看不到其中一个发生任何变化。给定 this 可能有办法做到这一点.但是,最好不要使用 Process,而是使用 Thread,参见 here .不同的是,根据this ,线程更适合 I/O 绑定(bind)操作,您的传感器肯定是这样。