July 2018
Intermediate to advanced
266 pages
7h 11m
English
More often than not, using withLock() will be enough for your needs. But in case you need more control of the locking and unlocking, you can use the suspending function lock() and the regular—as in non-suspending—function unlock():
val mutex = Mutex()mutex.lock() // this will suspend if the lock has been taken alreadyprint("I am now an atomic block")mutex.unlock() // this is not suspending
As a matter of fact, the implementation of withLock() is quite close to that. This is the current implementation of it:
lock(owner)try { return action()} finally { unlock(owner)}
You can use the property isLocked to validate whether the mutex is currently locked:
val mutex = Mutex()mutex.lock()mutex.isLocked // truemutex ...
Read now
Unlock full access