diff --git a/Mutex&Semaphore.pdf b/Mutex&Semaphore.pdf new file mode 100644 index 0000000..309d0a0 Binary files /dev/null and b/Mutex&Semaphore.pdf differ diff --git a/Mutex.kt b/Mutex.kt new file mode 100644 index 0000000..88b90b2 --- /dev/null +++ b/Mutex.kt @@ -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() +} diff --git a/Semaphore.kt b/Semaphore.kt new file mode 100644 index 0000000..c18fa0d --- /dev/null +++ b/Semaphore.kt @@ -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 { + + } +}