How to use lock_guard in C++

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
q.push(i);
}
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();
q.pop();
}
}
return i;
}

view raw
lock_guard_queue.cpp
hosted with ❤ by GitHub

Tried with: Visual C++ 2013

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.