dev qol: Add wait/notify functionality to ConcurrentQueue

This commit is contained in:
John Colvin committed 2025-06-16 11:08:56 -04:00
1 parent e6466f8309
commit edc2cea60e
1 file changed
+105 -8
@@ -1,5 +1,10 @@
#pragma once
#include "spark/core/TimeSpan.h"
#include "spark/core/TimeStamp.h"
#include <condition_variable>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
@@ -10,6 +15,8 @@ template <class T>
class ConcurrentQueue {
std::mutex mx;
std::queue<T> queue;
std::condition_variable cv;
bool has_items;
public:
bool empty() {
@@ -17,29 +24,119 @@ class ConcurrentQueue {
return queue.empty();
}
void push(T item) {
std::lock_guard<std::mutex> lock{mx};
void push(T item, bool notify = true) {
mx.lock();
queue.push(std::move(item));
if (notify && !has_items) {
has_items = true;
mx.unlock();
cv.notify_all();
} else {
mx.unlock();
}
}
bool pop(T &res) {
std::lock_guard<std::mutex> lock{mx};
template <typename Iter>
void push_many(Iter first, Iter last, bool notify = true) {
mx.lock();
while (first != last) {
queue.push(*first++);
}
if (notify && !has_items) {
has_items = true;
mx.unlock();
cv.notify_all();
} else {
mx.unlock();
}
}
bool pop(T &res, bool notify = true) {
mx.lock();
if (queue.empty()) {
mx.unlock();
return false;
}
res = std::move(queue.front());
queue.pop();
if (notify && has_items == queue.empty()) {
has_items = !has_items;
mx.unlock();
cv.notify_all();
} else {
mx.unlock();
}
return true;
}
std::optional<T> pop() {
std::lock_guard<std::mutex> lock{mx};
std::optional<T> pop(bool notify = true) {
mx.lock();
if (queue.empty()) {
mx.unlock();
return std::nullopt;
}
std::optional<T> rv = std::move(queue.front());
T res = std::move(queue.front());
queue.pop();
return rv;
if (notify && has_items == queue.empty()) {
has_items = !has_items;
mx.unlock();
cv.notify_all();
} else {
mx.unlock();
}
return res;
}
std::optional<T> wait_until_pop(bool notify = true) {
std::optional<T> res = pop(notify);
while (!res) {
wait();
res = pop(notify);
}
return res;
}
std::optional<T> wait_for_until_pop(
bts::core::TimeSpan timeout, bool notify = true) {
std::optional<T> res = pop(notify);
if (res) {
return res;
}
auto now = bts::core::TimeStamp::now();
const bts::core::TimeStamp give_up_time = now + timeout;
while (!res && now < give_up_time) {
wait_for(give_up_time - now);
res = pop(notify);
}
return res;
}
bool wait() {
std::unique_lock<std::mutex> lock{mx};
cv.wait(lock, [&]() { return has_items; });
return has_items;
}
bool wait_for(bts::core::TimeSpan timeout) {
std::unique_lock<std::mutex> lock{mx};
cv.wait_for(lock, timeout.to_chrono_ns(), [&]() { return has_items; });
return has_items;
}
/**
* Manually notify waiters if the queue's empty status has changed.
*
*/
void notify_waiters() {
mx.lock();
if (has_items == queue.empty()) {
has_items = !has_items;
mx.unlock();
cv.notify_all();
} else {
mx.unlock();
}
}
};
} // namespace bts::collections