February 2018
Intermediate to advanced
350 pages
7h 35m
English
A Mutex (mutual exclusion) object allows access to multiple coroutines to share the same resource but not simultaneously:
import kotilnx.coroutines.experimental.sync.Muteximport kotlinx.coroutines.experimental.sync.withLockfun main(args: Array<String>) = runBlocking { val mutex = Mutex() var counter = 0 val time = measureTimeMillis { repeatInParallel(1_000_000) { mutex.withLock { counter++ } } } println("counter = $counter") println("time = $time")}
A Mutex object works similarly to a synchronized control structure, but, instead of blocking the thread, it just blocks the coroutine.
Read now
Unlock full access