Documentation says that providing mosquitto_publish()
with pointer to mid
allows tracking for completion of the message sending. I am making architecture for serial message sending to prevent data loss in memory in case of power failure. So generally I am expected to take value of mid
, and have some code in the publish callback comparing this message id to the arriving callbacks, and raise a flag of completion.
The problem here I can’t clear is one thread calling mosquitto_publish()
and another thread performing manual mosquitto looping. Therefore callbacks are initiated in another thread than mosquitto_publish()
.
Example:
Thread 1:
volatile sig_atomic_t midPublish;
void somefunc(void)
{
...
mosquitto_publish(..., &midPublish, ...);
...
}
Thread 2:
extern volatile sig_atomic_t midPublish;
void publish_callback(struct mosquitto *mosq, void *userdata, int mid)
{
....
if(mid == midPublish)
{
...
}
...
}
The compiler says
warning: passing argument 2 of ‘mosquitto_publish’ discards ‘volatile’ qualifier from pointer target type
and it is actually correct. While atomicity can be achieve here on this platform, volatility seems can’t and I am afraid of effects of just casting &(int*)midPublish
will lead to actual optimized code not to get proper values from the variables/related memory locations.
Any advice?
Edit: one of the possible solutions is to synchronize threads by one thread passing data to publish onto the MQTT thread, and then MQTT thread in its manual loop calling mosquitto_publish()
with following mosquitto_loop()
call therefore publish and callback will be physically separate in their execution time.