Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created January 14, 2015 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ashwin/3524a8e833b790e3d6f0 to your computer and use it in GitHub Desktop.
Save ashwin/3524a8e833b790e3d6f0 to your computer and use it in GitHub Desktop.
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
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment