Skip to content

Instantly share code, notes, and snippets.

@jepio
Forked from ashwin/lock_guard_queue.cpp
Last active August 29, 2015 14:14
Show Gist options
  • Save jepio/e23dcf3872fa933af798 to your computer and use it in GitHub Desktop.
Save jepio/e23dcf3872fa933af798 to your computer and use it in GitHub Desktop.
#include <mutex>
#include <queue>
#include <iostream>
std::queue<int> q; // Queue which multiple threads might add/remove from
std::mutex m; // Mutex to protect this queue
template <class F> void lock(std::mutex& mut_ex, F f)
{
std::lock_guard<std::mutex> guard{ mut_ex }; // Lock held from here to end of function
f();
}
void AddToQueue(int i) { lock(m, [&] { q.push(i); }); }
int RemoveFromQueue()
{
int i = -1;
lock(m, [&] {
if (!q.empty()) {
i = q.front();
q.pop();
}});
return i;
}
template <typename T>
class QueueIterator {
using myQueue = std::queue < T > ;
public:
QueueIterator(myQueue& queue) : queue_(queue) { }
QueueIterator& operator++() { queue_.pop(); return *this; }
T operator*() { return queue_.front(); }
bool operator!=(QueueIterator const& other) { return !queue_.empty(); }
private:
myQueue& queue_;
};
namespace std {
template <typename T>
QueueIterator<T> begin(std::queue<T>& queue) { return{ queue }; }
template <typename T>
QueueIterator<T> end(std::queue<T>& queue) { return{ queue }; }
}
int main()
{
auto elements = { 1, 2, 3, 4 };
for (auto&& e : elements)
AddToQueue(e);
RemoveFromQueue();
RemoveFromQueue();
for (auto&& e: q)
std::cout << e << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment