Sobes.tech
Junior — Middle

Can you explain what the term 'mutex' means and how it is used for thread synchronization?

sobes.tech AI

Answer from AI

Mutex (mutual exclusion) — is a synchronization mechanism used to prevent multiple threads from simultaneously accessing a shared resource (for example, a variable or data structure). It guarantees that only one thread can own the mutex and execute the critical section of code at a time.

Working principle:

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

Example in C++ using std::mutex:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int counter = 0;

void increment() {
    mtx.lock(); // acquire mutex
    ++counter;
    std::cout << "Counter: " << counter << std::endl;
    mtx.unlock(); // release mutex
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    return 0;
}

In this example, the mutex protects the variable counter from being modified simultaneously by multiple threads, preventing a race condition.