Created
January 14, 2015 01:53
-
-
Save ashwin/3524a8e833b790e3d6f0 to your computer and use it in GitHub Desktop.
Example of using lock_guard to control concurrent access to a queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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