Sobes.tech
Junior — Middle

What is the main function of a mutex in a multithreaded environment?

sobes.tech AI

Answer from AI

A mutex (mutual exclusion) is used to synchronize access to shared resources in a multithreaded environment. Its main function is to ensure that only one thread can execute a critical section of code at any given time, thereby preventing race conditions and ensuring data integrity.

Example in C++ using std::mutex:

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

std::mutex mtx;
int counter = 0;

void increment() {
    mtx.lock();            // Lock the mutex
    ++counter;             // Critical section
    mtx.unlock();          // Unlock the mutex
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();
    std::cout << "Counter: " << counter << std::endl;
    return 0;
}

Without a mutex, both threads could modify counter simultaneously, leading to incorrect results.