Mutual exclusions
So far, we have avoided atomicity violation by guaranteeing that all memory access in a block of code happens in a single thread. But there's yet another way for us to avoid two blocks of code from being executed concurrently: mutual exclusions.
Understanding mutual exclusions
We are looking for ways to synchronize a block of code so that it's not executed concurrently, thus eliminating the risk of atomicity violation. Mutual exclusion refers to a synchronization mechanism that guarantees that only one coroutine can execute a block of code at a time.
The most important characteristic of Kotlin's mutexes is that they are not blocking: the coroutines waiting to be executed will be suspended until they can acquire the lock and execute the block of code. Nevertheless, it's possible to lock a mutex without being in a suspending function.
Note
If you are familiar with Java, you can think of a mutex as a non-blocking synchronized
.
Creating mutexes
To create a mutex, you only need to...