【问题标题】:Access an attribute of the same object in two functions running at the same time在同时运行的两个函数中访问同一对象的属性
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2012-08-04
    • 2019-01-31
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多