Concurrent coordination is a notoriously difficult problem: how do we make the behavior of a computation depend on another, concurrently running one? Or more than one? We’ll show one technique: the concurrent state machine, and build many examples using the powerful Cats Effect library.
For example, how can we share state between effects when that state might be concurrently updated? Or how can we ensure one effect only proceeds once work is complete in another? We’ll discuss the first issue by using the Ref data type for sharing mutable state. We’ll then show how the Deferred data type can provide concurrent effect serialization without blocking any actual threads. Finally we’ll model even more complex behavior by composing these two concurrency primitives together to form a concurrent state machine.
Some concurrent coordination behaviors we can construct using this method are:
mutual exclusion (mutexes, semaphores, etc.)
latches (closed until a certain number of events happen, then always open)
and many others.