【发布时间】:2018-09-27 18:24:01
【问题描述】:
您好,我遇到了一个奇怪的问题,也许有人可以提供帮助, 我首先使用相同的参数运行 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()
【问题讨论】:
-
看来您的问题与
sensor.sense()的行为有关。你有可以提供关于这种方法的文档吗? -
我已经编辑了帖子
标签: python object multiprocessing visibility