-
-
Save jepio/e23dcf3872fa933af798 to your computer and use it in GitHub Desktop.
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> | |
#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