Sobes.tech
Junior — Middle

Can you explain how mutual exclusion (mutex) works and how it ensures safety when working with shared resources?

sobes.tech AI

Answer from AI

Mutual exclusion (mutex) is a synchronization mechanism that guarantees that at any given moment, only one thread can access a shared resource (such as a variable, file, or code section). This prevents race conditions, where multiple threads modify data simultaneously, which can lead to errors.

Working principle:

  • A thread that wants to access the resource attempts to acquire the mutex.
  • If the mutex is free, the thread acquires it and continues working.
  • If the mutex is already held by another thread, the current thread is blocked and waits for it to be released.
  • After finishing with the resource, the thread releases the mutex, allowing other threads to access it.

Thus, mutex ensures safety when working with shared resources, guaranteeing sequential access and preventing simultaneous modifications.

Example in Kotlin for Android:

val mutex = Mutex()

suspend fun safeIncrement(counter: MutableState<Int>) {
    mutex.lock()
    try {
        counter.value += 1
    } finally {
        mutex.unlock()
    }
}

Here, the mutex guarantees that the counter modification occurs atomically.