C++ mutex lock/unlock

A mutex (short for mutual exclusion) is a synchronization primitive that is used to protect shared resources from concurrent access by multiple threads. In C++, the <mutex> header provides the necessary tools to implement mutexes.

To lock a mutex, you can use the lock() method of the std::mutex class. This method blocks the calling thread until it can obtain exclusive ownership of the mutex. If the mutex is already locked by another thread, the calling thread will be suspended until the lock is released.

Once a thread has finished using the shared resource, it should unlock the mutex to allow other threads to access it. This can be done using the unlock() method of the std::mutex class. Unlocking a mutex that is not currently locked by the calling thread results in undefined behavior.

Here is an example that demonstrates the usage of mutex lock and unlock:

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

std::mutex mtx;

void sharedResourceAccess()
{
    // Lock the mutex
    mtx.lock();

    // Access the shared resource
    std::cout << "Thread " << std::this_thread::get_id() << " is accessing the shared resource." << std::endl;

    // Simulate some work
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // Unlock the mutex
    mtx.unlock();
}

int main()
{
    // Create multiple threads to access the shared resource
    std::thread t1(sharedResourceAccess);
    std::thread t2(sharedResourceAccess);

    // Wait for the threads to finish
    t1.join();
    t2.join();

    return 0;
}

In this example, the sharedResourceAccess() function represents the code that needs to be protected by a mutex. The mtx mutex is used to synchronize access to the shared resource. When a thread enters the sharedResourceAccess() function, it locks the mutex using mtx.lock(). Once it has finished accessing the shared resource, it unlocks the mutex using mtx.unlock(). This ensures that only one thread can access the shared resource at a time, preventing data races and ensuring thread safety.

Note that it's important to always unlock the mutex after it has been locked to avoid deadlocks or blocking other threads indefinitely.