Daily bit(e) of C++ | std::mutex
Daily bit(e) of C++ ♻️12, The mutual exclusion lock for protecting shared resources: std::mutex.
std::mutex is a mutual exclusion lock that permits only one owning thread to hold the lock, protecting a shared resource from simultaneous access by multiple threads.
A std::mutex can be manually locked by calling either lock or try_lock. Succesive calls to lock on other threads will block, and calls to try_lock will return false until the owning thread unlocks the std::mutex by calling unlock.
Note that calling lock or try_lock on a thread that already holds the lock or calling unlock on a thread that doesn't hold the lock is not permitted. Additionally, destroying a mutex while locked is also UB.
Because manually unlocking the std::mutex is potentially error-prone, using an RAII-based wrapper such as std::unique_lock is highly recommended.