Junior — Middle
Milliseid meetodeid kasutatakse korutinate turvalise ja jagatud juurdepääsu korraldamiseks ühele ressursile?
sobes.tech AI
Vastus AI-lt
For safe shared access of coroutines to a resource in Android (Kotlin), the following methods are commonly used:
- Mutex from kotlinx.coroutines — provides mutual exclusion, allowing only one coroutine at a time to access the resource.
- Channel — for data transfer between coroutines, helping to avoid direct shared access.
- Atomic operations — for simple cases where it is necessary to safely update primitive values.
Example of using Mutex:
val mutex = Mutex()
var sharedResource = 0
suspend fun safeIncrement() {
mutex.withLock {
sharedResource++
}
}
This approach prevents race conditions and ensures correct behavior during parallel execution of coroutines.