Sobes.tech
Junior — Middle

Can some types of Lock Guard implemented in the C++ standard library be named?

sobes.tech AI

Answer from AI

The C++ standard library implements several types of Lock Guard that provide convenient and safe management of mutexes and other synchronization primitives:

  • std::lock_guard — a simple RAII wrapper for locking a mutex for the lifetime of an object. It automatically locks the mutex upon creation and unlocks it upon destruction.

  • std::unique_lock — a more flexible class that allows delaying locking, unlocking, and re-locking a mutex, as well as transferring ownership.

Example of using std::lock_guard:

#include <mutex>

std::mutex mtx;

void thread_safe_function() {
    std::lock_guard<std::mutex> lock(mtx); // mutex is locked
    // critical section
} // mutex is automatically unlocked when leaving scope

std::unique_lock is used when additional flexibility is needed:

#include <mutex>

std::mutex mtx;

void flexible_lock() {
    std::unique_lock<std::mutex> lock(mtx, std::defer_lock); // do not lock immediately
    // ...
    lock.lock(); // lock the mutex
    // critical section
    lock.unlock(); // unlock
    // ...
}