ccls/src/threaded_queue.h

55 lines
1.2 KiB
C
Raw Normal View History

2017-03-25 19:18:25 +00:00
#pragma once
2017-03-25 20:32:44 +00:00
#include <optional.h>
2017-03-25 19:18:25 +00:00
#include <algorithm>
#include <queue>
#include <mutex>
#include <condition_variable>
2017-03-25 20:32:44 +00:00
// TODO: cleanup includes.
2017-03-25 19:18:25 +00:00
// A threadsafe-queue. http://stackoverflow.com/a/16075550
template <class T>
class ThreadedQueue {
public:
// Add an element to the queue.
void Enqueue(T&& t) {
2017-03-25 19:18:25 +00:00
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(std::move(t));
2017-03-25 19:18:25 +00:00
cv_.notify_one();
}
// Get the "front"-element.
2017-03-25 20:32:44 +00:00
// If the queue is empty, wait untill an element is avaiable.
2017-03-25 19:18:25 +00:00
T Dequeue() {
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.empty()) {
// release lock as long as the wait and reaquire it afterwards.
cv_.wait(lock);
}
auto val = std::move(queue_.front());
2017-03-25 19:18:25 +00:00
queue_.pop();
return val;
}
2017-03-25 20:32:44 +00:00
// Get the first element from the queue without blocking. Returns a null
// value if the queue is empty.
2017-03-25 19:18:25 +00:00
optional<T> TryDequeue() {
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.empty())
return nullopt;
auto val = std::move(queue_.front());
2017-03-25 19:18:25 +00:00
queue_.pop();
return val;
}
2017-03-25 20:32:44 +00:00
private:
2017-03-25 19:18:25 +00:00
std::queue<T> queue_;
mutable std::mutex mutex_;
std::condition_variable cv_;
};