Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KjellKod/c3881ff1a56a3ef3b618 to your computer and use it in GitHub Desktop.
Save KjellKod/c3881ff1a56a3ef3b618 to your computer and use it in GitHub Desktop.
// 2015 by KjellKod.cc
// A lock-free in-place version of the shared-queue used in g2log and g3log
// instead of the normal shared-queue https://github.com/KjellKod/g3log/blob/e219a5e426d329a4a4c85aee92ec6eacc43a7125/src/shared_queue.hpp
// it wraps Moody Camel's lock-free queue
// http://moodycamel.com/blog/2014/detailed-design-of-a-lock-free-queue
#pragma once
#include "concurrentqueue.hpp"
#include <thread>
/** Multiple producer, multiple consumer thread safe queue
* Since 'return by reference' is used this queue won't throw */
template<typename T>
class shared_queue
{
moodycamel::ConcurrentQueue<T> queue_;
queue_;
shared_queue& operator=(const shared_queue&) = delete;
shared_queue(const shared_queue& other) = delete;
public:
shared_queue(){}
void push(T item){
queue_.enqueue(std::move(item));
}
/// Try to retrieve, if no items, wait till an item is available and try again
void wait_and_pop(T& popped_item){
while(true) {
if (queue_.try_dequeue(popped_item)) {
break;
}
else {
std::this_thread::yield();
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment