Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use lock_guard in C++

📅 2015-Jan-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, lock guard, mutex ⬩ 📚 Archive

A lock_guard simplifies the usage of mutex in C++. It holds a lock on its mutex from the time it is created to the end of its scope. This simplifies the writing of locking and unlocking code using a mutex.

See this earlier example for usage of a mutex to control concurrent access to a queue from multiple threads. Below is the same written using lock guard:

#include <mutex>
#include <queue>
std::queue<int> q; // Queue which multiple threads might add/remove from
std::mutex m; // Mutex to protect this queue
void AddToQueue(int i)
    std::lock_guard<std::mutex> lg(m); // Lock will be held from here to end of function
int RemoveFromQueue()
    int i = -1;
        std::lock_guard<std::mutex> lg(m); // Lock held from here to end of scope
        if (!q.empty())
            i = q.front();
    return i;

Tried with: Visual C++ 2013

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧