2

Hello i am having a weird issue maybe some one can help, I start by running 2 different function with the same argument which is an object that is already instantiated :

iotComponent.connectedSensors=sensorList
iotComponent.connectedHUIs=HUIList

Coap = multiprocessing.Process(target=runCoapSync,args=(iotComponent,))
huis = multiprocessing.Process(target=runHuis,args=(iotComponent,))
huis.start()
Coap.start()

then here are both functions :

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)

in the first function when sensor.sense() is called the value attribute inside data attribute of the sensor is updated.

But in the second function, iotDevice.connectedSensors[0].data.value is always equals to Zero. I find this behavior weird because this is the same object. Moreover if i add a line sensor.sense() in the second function the value gets updated but it is not the same as the value printed in first function.

EDIT 0 : here is the sense() method :

 def sense(self):
        pinMode(self.pinNumber, "INPUT")
        lightSensorValue = analogRead(self.pinNumber)
        self.data.timestamp=str(round(time.time(), 3))
        self.data.value=lightSensorValue

If someone as an idea that would be great !

SOLUTION : as said in the accepted answer i tried with threading and it worked like a charm :

Coap = threading.Thread(target=runCoapSync,args=(iotComponent,))
huis = threading.Thread(target=runHuis,args=(iotComponent,))
huis.start()
Coap.start()
FrozzenFinger
  • 1,482
  • 2
  • 14
  • 35

1 Answers1

1

See this answer. Essentially what's happening is that your data is "pickled" before being sent to the processes to have work done. When the objects are received, they're unpacked. Therefore, the objects are more cloned than passed around. Therefore, you're actually working with two separate copies of iotComponent, which explains why you can't actually see any change happening on one even though you "know" work is being done. There might be a way to do this, given this. However, it might be better to not use Process, but use Thread instead, see here. The difference is that, according to this, threads are better for I/O-bound operations, which your sensor certainly is.

Woody1193
  • 7,252
  • 5
  • 40
  • 90