Sobes.tech
Junior — Middle

Explain the principle of mutual exclusion (mutex) in the context of multithreaded programming.

sobes.tech AI

Answer from AI

Mutual exclusion (mutex) is a synchronization mechanism used to prevent multiple threads from simultaneously accessing a shared resource, such as a variable or data structure. A mutex guarantees that only one thread can use the resource at any given time, thereby preventing race conditions and ensuring data integrity.

Working principle:

  • A thread attempts to acquire the mutex before accessing the resource.
  • 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 the mutex to be released.
  • After finishing with the resource, the thread releases the mutex, allowing other threads to access it.

Example in Java:

import java.util.concurrent.locks.ReentrantLock;

public class Counter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock(); // acquire mutex
        try {
            count++;
        } finally {
            lock.unlock(); // release mutex
        }
    }

    public int getCount() {
        return count;
    }
}

In this example, ReentrantLock acts as a mutex, ensuring that only one thread can increment the counter at a time.

Explain the principle of mutual exclusion (mutex) in… - sobes.tech