Created
January 14, 2015 01:44
-
-
Save ashwin/44eb4b410991fd8a74f0 to your computer and use it in GitHub Desktop.
Example of using mutex to control concurrent access to a queue
This file contains 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) | |
{ | |
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