Daily bit(e) of C++ | std::mutex
1 min readJan 13, 2023
Daily bit(e) of C++ #12, The mutual exclusion lock std::mutex
std::mutex
is a mutual exclusion lock that permits only one owner to hold the lock. A successive attempt at obtaining the lock will block until the previous owner of the lock releases it.
While the mutex can be locked and unlocked manually, it is desirable to use the RAII-based std::unique_lock
instead, which will always correctly release a held lock, preventing accidental deadlocks.
#include <mutex>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
struct Shared {
int value;
std::mutex mux;
};
Shared shared{0,{}};
{
auto t1 = std::jthread([&shared]{
for (int i = 0; i < 10; i++) {
// obtain lock
std::unique_lock lock(shared.mux);
// modify shared state
shared.value += 10;
} // mutex unlocks as std::unique_lock is destroyed
});
auto t2 = std::jthread([&shared]{
for (int i = 0; i < 10; i++) {
// obtain lock
std::unique_lock lock(shared.mux);
// modify shared state
shared.value += 1;
} // mutex unlocks as std::unique_lock is destroyed
});
} // t1 && t2 a destroyed and joined
// shared.value == 110