Mutex und Semaphore
This commit is contained in:
BIN
Mutex&Semaphore.pdf
Normal file
BIN
Mutex&Semaphore.pdf
Normal file
Binary file not shown.
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()
|
||||||
|
}
|
||||||
14
Semaphore.kt
Normal file
14
Semaphore.kt
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import kotlinx.coroutines.sync.Semaphore
|
||||||
|
import kotlinx.coroutines.sync.withPermit
|
||||||
|
|
||||||
|
val semaphore = Semaphore(5, 5)
|
||||||
|
|
||||||
|
suspend fun main() {
|
||||||
|
semaphore.acquire() //reduces available permits, suspends when none available
|
||||||
|
semaphore.tryAcquire() //returns False if no permit available
|
||||||
|
semaphore.release() //releases permit, possible after acquire
|
||||||
|
|
||||||
|
semaphore.withPermit {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user