Mutual exclusion and thread-safeness in luup plugins

I’m writing a plugin that utilizes both timers (luup.call_timer) and actions through . There are critical sections in both.

My question, probably only answerable by MCV: within one Luup device, are timer-callbacks and actions executed serially in the same Lua thread, or is pre-emption possible?

I would rather not have to write my own mutex implementation, especially in a language that has no atomic test-and-set or compare-and-swap operations.

@futzle,
In MiOS, there is one Lua context per Device. Lua itself is not ThreadSafe within a single Lua context, so there is nothing that can be done within your Lua code to mutex (etc).

In UI4 this can result in Plugin crashes, and in some cases data corruption, when two “events” occur at the same time within the same Device, since there are minimal blocks preventing the corresponding Lua blocks from running at the same time.

If you have timers, [tt][/tt], [tt][/tt] blocks and startup code that can occur “at the same time” then you can run into this. In my case, it impacts just about every v2 Plugin I have, and frequently results in me having to restore from backup as various child devices get created incorrectly, or plugins break.

In UI5, this has been fixed, and the C-code prevents concurrent calls using a per Lua context mutex, and the execution threads are also per Lua context (instead of global) so that other devices aren’t necessarily blocked in their execution. The timeouts on these are also increased, which is why Vera restarts less often on blocking Lua calls - like those that the Ping sensor, and others, make.

With that in mind, looks like it would be foolish of me to even release this plugin on UI4, then. A pity. Thanks for the info; it’s exactly what I needed to know (and I’m glad I don’t have to implement Lamport’s Bakery Algorithm in Lua).

Yes, it’s an extremely nasty problem. If UI4 were to have a “bucket list” of fixes, this should be on it…

It has an inane ability to corrupt an environment (typically shows itself as new child devices created for an existing parent, which breaks scenes and Control Point attachments). If I’m developing a Plugin against my Vera2/UI4, which I do to validate my changes for both UI4 and UI5, this can corrupt the environment [roughly] every 2 days, requiring restore from Backup…