python - 在同时运行的两个函数中访问同一对象的属性
问题描述
您好,我遇到了一个奇怪的问题,也许有人可以提供帮助,我首先使用相同的参数运行 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
is 始终等于零。我觉得这种行为很奇怪,因为这是同一个对象。此外,如果我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()
解决方案
推荐阅读
- nagios - Nagios Tool,该工具的总运行时间
- mysql - MySql - Thread_stack 大小在 wamp 中没有改变
- mysql - Laravel 6 多数据库认证问题
- typescript - 在当前类中使用 Typescript 将类成员转换为字符串
- javascript - 在 react redux 应用程序中使用容器会产生不需要的渲染?
- python - Explode List containing many dictionaries in Pandas dataframe
- mongodb - How can I define Date in my defined mongoose Schema such as to return a nicely formated date and time?
- gitattributes - github-linguist 无法识别来自 .gitattributes 的供应商文件
- lua - 我无法通过数组并更改地图中的值
- xamarin - Listview 项目不显示在 xamarin