Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created January 14, 2015 01:44
Show Gist options
  • Save ashwin/44eb4b410991fd8a74f0 to your computer and use it in GitHub Desktop.
Save ashwin/44eb4b410991fd8a74f0 to your computer and use it in GitHub Desktop.
Example of using mutex 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)
{
m.lock();
q.push(i);
m.unlock();
}
int RemoveFromQueue()
{
int i = -1;
m.lock();
if (!q.empty())
{
i = q.front();
q.pop();
}
m.unlock();
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment