Created
December 27, 2020 18:38
-
-
Save Hoegy/2815312932a270a18d5b0bf405c3a062 to your computer and use it in GitHub Desktop.
Mutex for coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.Dispatchers.Default | |
import kotlinx.coroutines.sync.Mutex | |
import kotlinx.coroutines.sync.withLock | |
private val mutex = Mutex() // our hero ;-) | |
private var counterWithMutex = 0 | |
private var counterNoMutex = 0 | |
suspend fun main( ) { | |
val job1NoMutex = CoroutineScope(Default).launch { | |
for (i in 1..500) { | |
incrementCounterByTenNoMutex() | |
} | |
} | |
val job2NoMutex = CoroutineScope(Default).launch { | |
for (i in 1..500) { | |
incrementCounterByTenNoMutex() | |
} | |
} | |
val job3WithMutex = CoroutineScope(Default).launch { | |
for (i in 1..500) { | |
incrementCounterByTenWithMutex() | |
} | |
} | |
val job4WithMutex = CoroutineScope(Default).launch { | |
for (i in 1..500) { | |
incrementCounterByTenWithMutex() | |
} | |
} | |
joinAll(job1NoMutex, job2NoMutex, job3WithMutex, job4WithMutex) | |
println(" No Mutex Tally: $counterNoMutex") | |
println("With Mutex Tally: $counterWithMutex") | |
} | |
private suspend fun incrementCounterByTenWithMutex() { | |
mutex.withLock { | |
for (i in 0 until 10) { | |
counterWithMutex++ | |
} | |
} | |
} | |
private fun incrementCounterByTenNoMutex() { | |
for (i in 0 until 10) { | |
counterNoMutex++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment