package bhylu.lessons.k_mutex import kotlinx.coroutines.runBlocking import kotlinx.coroutines.launch import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock class SharedDesk(private val capacity: Int) { init { require(capacity >= 0) } private val mutex = Mutex() private var used = 0 suspend fun hireOne(): Boolean = mutex.withLock { if (used >= capacity) false else { used++; true } } suspend fun hired(): Int = mutex.withLock { used } } fun main() { runBlocking { val desk = SharedDesk(5) val results = BooleanArray(20) val jobs = List(20) { index -> launch(Dispatchers.Default) { results[index] = desk.hireOne() } } jobs.forEach { it.join() } println(results.count { it }) println(desk.hired()) } }