Making Particle Function Handler thread safe

I am looking for advice about how best to implement the following to avoid any chance of resetting a global variable before it is used in the application loop.

Application code has SYSTEM_THREAD(ENABLED).
The Loop() is implemented as a Finite State Machine model with a run state.

There is a Particle Function handler that checks the data string passed to it and acts on the command name and any data sent with it. Sometimes the extra data is required to be used outside of the Function handler in which case it is place in a global variable. In order to publish messages to confirm the changes made as a result of the command - the Particle Function handler saves the existing run state and then sets the runstate to handle publishing the confirmation message.

In the next loop the run state now calls a function to publish the message and the global variable is used. At the end of this function the run state is set back to the run state when the function handler was called.

My concern is that I could receive a function call more than once before the loop has run again and thus the global variable could be set to another value and the original call ‘lost’.

I guess a FIFO queue for the global variables could be implemented but this seems to be complicated. Hope that I have clearly enough explained the problem so someone can suggest a better and simpler approach to what must be a common problem?

Function handlers, subscription handlers, and serial event handlers are all dispatched out of the loop thread, either in the period between calls to your loop() or when Particle.process() is called, even when the system thread is enabled. So, in general, you don’t have to worry about thread safety in these callbacks.

@rickkas7 Thanks - you are highlighting the potential problem which I am referring to; that between calls to the loop() the function handler is called more than once, unless you are saying that the function handler can only process once per loop() run?

Sorry, I do see that you were asking a different question now.

I would add a queue in your specific case, because I would not depend on getting only one function call between loop calls.

Thanks - I was hoping to avoid that complexity :frowning: