Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of using lock_guard to control concurrent access to a queue
#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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.