SL agent uses "threads" for sensors: need to protect shared resources | Thales IoT Developer Community
July 16, 2015 - 8:08pm, 2519 views
I am writing this for the "next person" who might find this problem. In our implementation there are mutliple sensors all on the I2C. And so this is a shared resource among many sensors. It appears that the class AnalogSensor uses one thread for each sensor -- that is logical, since each sensor has its own time base for sampling and reporting. But it is not described in any of the documentation (sensorlogic_agent_ug_v01a.pdf) or JavaDoc.
However if multiple sensors access a shared resource, such as I2C (or any object) there can be access problems due to concerrency issues. So the implementation has to protect for that (in embedded real time systems: a mutex). There is a simple solution that seems to work very well: Java synchronized methods. Just add the key word "synchonized" to any shared method/object. For example "
public synchronized void I2C_Selector() {
"
Read more here: http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
I suggest an update to the SL agent user's guide (sensorlogic_agent_ug_v01a.pdf) to describe this part of the SL agent. This concurrency problem probably will most likely affect most users of the SL agent. You may not see the problem, it depends on the sampling rate settings for each sensor. But there is always a probability that it will happen, there will be some unknown exception, and it will be a mystery unless you know what to look for.
I think I have this understood, but if someone has more insight or clarifications, please add some notes.
Thank you.
Roland
Hello,
Thank you for your comments.
You are right that each sensor has its own thread inside for monitoring its value. And you are right that it is not stressed in the user documentation that there is a separate thread inside. Generally there are no details about the internal implementation.
In fact to have more than one analogue sensor you have to create a separate class for each one. And if each instance of each class will need to use the same resource the access should be synchronized unless we are sure that only one thread will be using the resource.
I agree that these kinds of problems are hard to debug so if that information in documentation could help to avoid it I agree that it's worth adding.
Regards,
Bartłomiej