riot
riot copied to clipboard
Riot-friendly mutex
I volunteered for issue #46, but have been blocked on this and haven't heard from the person previously working on it, so I thought I'd pick it up :)
There were a few decisions I made that I'm not super sure of so definitely a draft! Feedback v much appreciated!
It seems to work, though I have observed the mutex process hanging if there are a lot of processes trying to get the lock. Not sure if that's specific to this or a larger issue w/ Riot.
The basic idea (which was partly inspired by the previous implementation) is:
-
create
spawns a looping process behind the scenes and returns a handle -
lock
takes this handle and a function, and sends aLock
message to the mutex - If unlocked, the mutex process responds with an
Accepted
message, otherwise, it enqueues the PID of the process attempting to lock - Once the lock is acquired, the inner value (contained in the handle) is set to
f mutex.inner
- The locker sends an
Unlock
message, the mutex process sends anUnlock_accepted
-
lock
returnsOk ()
, the mutex process checks the queue and starts looping again -
get
is identical tolock
but instead of mutating the inner it returns a deep copy of it - Functions prefixed with
try
immediately return an error if the mutex is locked, as opposed to waiting
Both the locking process and the mutex process monitor each other to prevent deadlocks that could be caused if one crashes while the other waits. The mutex process handles double locks/unlocks, other invalid messages, with a Failed (reason)
message. Every function in the API, besides unsafe get and set, return a result so the locking thread can handle failures.
Some questions that came up while writing this:
- Should the mutex process fail on an invalid message?
- Do we want
create
to take an optionalpriority
that's applied to the mutex process? - do we want
unsafe_get
andunsafe_set
? - Should cloning be done by serializing and deserializing via
Marshal
or usingObj
? The latter seems tricky but less expensive - Does the error type need to be a polymorphic variant? I noticed a lot of the other errors in the lib are and figured that was for a reason but idk further than that
- tests?