Mutex und Semaphore
This commit is contained in:
62
Mutex.kt
Normal file
62
Mutex.kt
Normal file
@@ -0,0 +1,62 @@
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
suspend fun massiveRun(action: suspend () -> Unit) {
|
||||
val n = 100 // number of coroutines to launch
|
||||
val k = 1000 // times an action is repeated by each coroutine
|
||||
val time = measureTimeMillis {
|
||||
coroutineScope { // scope for coroutines
|
||||
repeat(n) {
|
||||
launch {
|
||||
repeat(k) { action() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println("Completed ${n * k} actions in $time ms")
|
||||
}
|
||||
|
||||
var counter = 0
|
||||
|
||||
fun withoutMutex() = runBlocking {
|
||||
withContext(Dispatchers.Default) {
|
||||
massiveRun {
|
||||
counter++
|
||||
}
|
||||
}
|
||||
println("Counter = $counter")
|
||||
}
|
||||
|
||||
val mutex = Mutex()
|
||||
suspend fun x() {
|
||||
mutex.lock() //suspends until mutex is unlocked
|
||||
mutex.tryLock() //returns false if mutex is locked
|
||||
mutex.unlock() //unlocks mutex
|
||||
mutex.withLock {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
fun withMutex() = runBlocking {
|
||||
withContext(Dispatchers.Default) {
|
||||
massiveRun {
|
||||
mutex.withLock {
|
||||
var c = counter
|
||||
c +=1;
|
||||
counter = c
|
||||
}
|
||||
}
|
||||
}
|
||||
println("Counter = $counter")
|
||||
}
|
||||
|
||||
fun main() {
|
||||
withoutMutex()
|
||||
//withMutex()
|
||||
}
|
||||
Reference in New Issue
Block a user