mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 22:51:11 +00:00
delay_ms is a uint32_t, so 0xFFFFFFFF is a valid delay. When the remaining time was exactly 0xFFFFFFFF, wait_until passed INFINITE to Win32 Sleep, which waits forever: the loop never re-checked the deadline and the callback never fired on the lanes that sleep out the remainder themselves. Factor the chunk calculation into finite_sleep_chunk_ms in task_queue.h, which clamps every chunk to at most INFINITE - 1 (0xFFFFFFFE) and is always positive. The test asserts the clamp for a 0xFFFFFFFF remainder without waiting 49 days, and that a 0xFFFFFFFF delay is accepted and its callback fires on the parallel and manual lanes. Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
327 lines
12 KiB
C++
327 lines
12 KiB
C++
#include "task_queue.h"
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <condition_variable>
|
|
#include <mutex>
|
|
#include <new>
|
|
#include <unordered_map>
|
|
|
|
namespace bx::gdk {
|
|
|
|
class Queue : public std::enable_shared_from_this<Queue> {
|
|
public:
|
|
struct Lane {
|
|
Queue* owner;
|
|
DispatchMode mode;
|
|
PTP_WORK worker = nullptr;
|
|
std::mutex mutex;
|
|
std::condition_variable ready;
|
|
std::unique_ptr<Task> first;
|
|
Task* last = nullptr;
|
|
// Keep the queue alive while Windows has outstanding worker callbacks.
|
|
QueueRef worker_owner;
|
|
size_t workers = 0;
|
|
bool serial_running = false;
|
|
bool closed = false;
|
|
|
|
Lane(Queue* owner, DispatchMode mode) : owner(owner), mode(mode) {}
|
|
|
|
~Lane() {
|
|
if (worker) CloseThreadpoolWork(worker);
|
|
while (first) pop();
|
|
}
|
|
|
|
HRESULT initialize() {
|
|
if (mode == DispatchMode::parallel || mode == DispatchMode::serialized) {
|
|
worker = CreateThreadpoolWork(run_worker, this, nullptr);
|
|
if (!worker) return HRESULT_FROM_WIN32(GetLastError());
|
|
}
|
|
return S_OK;
|
|
}
|
|
|
|
bool push(std::unique_ptr<Task> task, bool is_completion) {
|
|
std::unique_lock lock(mutex);
|
|
if (closed && !is_completion) return false;
|
|
if (mode == DispatchMode::immediate || (closed && mode == DispatchMode::manual)) {
|
|
// No lane storage on these paths, so the submitting thread waits out
|
|
// the remainder of the delay and then runs the callback itself.
|
|
const uint64_t due_ms = task->due_ms;
|
|
lock.unlock();
|
|
wait_until(due_ms);
|
|
task->run(owner->shared_from_this());
|
|
return true;
|
|
}
|
|
auto* tail = task.get();
|
|
(last ? last->next : first) = std::move(task);
|
|
last = tail;
|
|
ready.notify_one();
|
|
|
|
if (mode == DispatchMode::parallel) schedule();
|
|
schedule_serial();
|
|
return true;
|
|
}
|
|
|
|
void schedule() {
|
|
if (workers++ == 0) worker_owner = owner->shared_from_this();
|
|
SubmitThreadpoolWork(worker);
|
|
}
|
|
|
|
bool due() const { return first && (first->due_ms == 0 || GetTickCount64() >= first->due_ms); }
|
|
|
|
// Sleep out the remainder of a GetTickCount64 deadline. Saturating: the
|
|
// deadline can pass between the check and the clock read, and an unsigned
|
|
// subtraction there would wrap to ~584 million years.
|
|
static void wait_until(uint64_t due_ms) {
|
|
for (;;) {
|
|
const uint64_t now = GetTickCount64();
|
|
if (due_ms == 0 || now >= due_ms) return;
|
|
const uint64_t left = due_ms - now;
|
|
// INFINITE would mean "wait forever", so a `left` of exactly
|
|
// 0xFFFFFFFF would never wake to re-check the deadline.
|
|
Sleep(finite_sleep_chunk_ms(left));
|
|
}
|
|
}
|
|
|
|
// FIFO: the head holds the lane until it is due, so a later task never
|
|
// overtakes a delayed one. Wait only until that deadline, never spin.
|
|
std::chrono::steady_clock::time_point head_due() const {
|
|
const uint64_t now = GetTickCount64();
|
|
const uint64_t left = first->due_ms > now ? first->due_ms - now : 0;
|
|
return std::chrono::steady_clock::now() + std::chrono::milliseconds(left);
|
|
}
|
|
|
|
void schedule_serial() {
|
|
if (mode == DispatchMode::serialized && first && !serial_running && workers == 0) {
|
|
schedule();
|
|
}
|
|
}
|
|
|
|
std::unique_ptr<Task> pop() {
|
|
auto task = std::move(first);
|
|
first = std::move(task->next);
|
|
if (!first) last = nullptr;
|
|
return task;
|
|
}
|
|
|
|
void close(const QueueRef& queue) {
|
|
std::unique_lock lock(mutex);
|
|
closed = true;
|
|
ready.notify_all();
|
|
if (mode != DispatchMode::manual) return;
|
|
|
|
while (first) {
|
|
auto task = pop();
|
|
lock.unlock();
|
|
task->cancel(queue);
|
|
lock.lock();
|
|
}
|
|
}
|
|
|
|
bool dispatch(uint32_t timeout) {
|
|
if (mode == DispatchMode::immediate) return false;
|
|
std::unique_lock lock(mutex);
|
|
const auto has_task = [this] { return closed || (due() && !serial_running); };
|
|
if (timeout == INFINITE) {
|
|
while (!has_task()) {
|
|
if (first && !serial_running) {
|
|
ready.wait_until(lock, head_due());
|
|
} else {
|
|
ready.wait(lock);
|
|
}
|
|
}
|
|
} else {
|
|
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
|
|
while (!has_task()) {
|
|
if (std::chrono::steady_clock::now() >= deadline) return false;
|
|
auto wake = deadline;
|
|
if (first && !serial_running) {
|
|
wake = std::min(wake, head_due());
|
|
}
|
|
ready.wait_until(lock, wake);
|
|
}
|
|
}
|
|
if (closed) return false;
|
|
auto task = pop();
|
|
if (mode == DispatchMode::serialized) serial_running = true;
|
|
lock.unlock();
|
|
task->run(owner->shared_from_this());
|
|
if (mode == DispatchMode::serialized) {
|
|
lock.lock();
|
|
serial_running = false;
|
|
schedule_serial();
|
|
ready.notify_all();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static void CALLBACK run_worker(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) {
|
|
auto& lane = *static_cast<Lane*>(context);
|
|
QueueRef queue;
|
|
std::unique_lock lock(lane.mutex);
|
|
queue = lane.worker_owner;
|
|
while (lane.first && !lane.serial_running) {
|
|
// A delayed head must not run early. Wait on the condition variable
|
|
// until its deadline (or a push changes the head) instead of popping
|
|
// it, so FIFO order holds and nothing is dropped. Close drains what
|
|
// was already accepted, as it did before delays existed.
|
|
if (!lane.closed && !lane.due()) {
|
|
lane.ready.wait_until(lock, lane.head_due());
|
|
continue;
|
|
}
|
|
auto task = lane.pop();
|
|
const bool serial = lane.mode == DispatchMode::serialized;
|
|
lane.serial_running = serial;
|
|
lock.unlock();
|
|
task->run(queue);
|
|
lock.lock();
|
|
lane.serial_running = false;
|
|
if (!serial) break;
|
|
}
|
|
if (--lane.workers == 0) lane.worker_owner.reset();
|
|
}
|
|
};
|
|
|
|
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
|
|
|
|
Lane lanes[2];
|
|
};
|
|
|
|
namespace {
|
|
|
|
std::mutex queues_mutex;
|
|
std::unordered_map<uintptr_t, QueueRef> handles;
|
|
uintptr_t next_handle = 1;
|
|
QueueRef process_queue;
|
|
|
|
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
|
|
auto candidate = std::make_shared<Queue>(work, completion);
|
|
for (auto& lane : candidate->lanes) {
|
|
const HRESULT hr = lane.initialize();
|
|
if (FAILED(hr)) return hr;
|
|
}
|
|
queue = std::move(candidate);
|
|
return S_OK;
|
|
}
|
|
|
|
void* add_handle(const QueueRef& queue) {
|
|
const auto id = next_handle;
|
|
next_handle += 2;
|
|
handles.emplace(id, queue);
|
|
return reinterpret_cast<void*>(id);
|
|
}
|
|
|
|
struct CallbackTask final : Task {
|
|
using Callback = void (CALLBACK*)(void*, bool);
|
|
Callback callback;
|
|
void* context;
|
|
|
|
CallbackTask(Callback callback, void* context) : callback(callback), context(context) {}
|
|
void run(const QueueRef&) override { callback(context, false); }
|
|
void cancel(const QueueRef&) override { callback(context, true); }
|
|
};
|
|
|
|
} // namespace
|
|
|
|
QueueRef acquire_queue(void* handle) {
|
|
std::lock_guard lock(queues_mutex);
|
|
if (!handle) {
|
|
try {
|
|
if (!process_queue) make_queue(DispatchMode::parallel, DispatchMode::parallel, process_queue);
|
|
} catch (const std::bad_alloc&) {
|
|
return {};
|
|
}
|
|
return process_queue;
|
|
}
|
|
const auto it = handles.find(reinterpret_cast<uintptr_t>(handle));
|
|
return it == handles.end() ? QueueRef{} : it->second;
|
|
}
|
|
|
|
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
|
|
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
|
}
|
|
|
|
|
|
} // namespace bx::gdk
|
|
|
|
using namespace bx::gdk;
|
|
|
|
extern "C" {
|
|
|
|
HRESULT WINAPI XTaskQueueCreate(DispatchMode work, DispatchMode completion, void** out) {
|
|
if (!out) return E_POINTER;
|
|
*out = nullptr;
|
|
if (work > DispatchMode::immediate || completion > DispatchMode::immediate) return E_INVALIDARG;
|
|
|
|
try {
|
|
QueueRef queue;
|
|
const auto hr = make_queue(work, completion, queue);
|
|
if (FAILED(hr)) return hr;
|
|
std::lock_guard lock(queues_mutex);
|
|
*out = add_handle(queue);
|
|
return S_OK;
|
|
} catch (const std::bad_alloc&) {
|
|
return E_OUTOFMEMORY;
|
|
}
|
|
}
|
|
|
|
void WINAPI XTaskQueueCloseHandle(void* handle) {
|
|
QueueRef queue;
|
|
bool close_queue = false;
|
|
{
|
|
std::lock_guard lock(queues_mutex);
|
|
const auto it = handles.find(reinterpret_cast<uintptr_t>(handle));
|
|
if (it == handles.end()) return;
|
|
queue = std::move(it->second);
|
|
close_queue = queue != process_queue;
|
|
handles.erase(it);
|
|
}
|
|
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
|
|
// completion callbacks on close and let accepted pool work finish normally.
|
|
if (close_queue) {
|
|
for (auto& lane : queue->lanes) lane.close(queue);
|
|
}
|
|
}
|
|
|
|
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
|
if (!handle || port > Port::completion) return false;
|
|
const auto queue = acquire_queue(handle);
|
|
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
|
}
|
|
|
|
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
|
CallbackTask::Callback callback);
|
|
|
|
HRESULT WINAPI XTaskQueueSubmitCallback(void* handle, Port port, void* context, CallbackTask::Callback callback) {
|
|
return XTaskQueueSubmitDelayedCallback(handle, port, 0, context, callback);
|
|
}
|
|
|
|
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
|
CallbackTask::Callback callback) {
|
|
if (!handle || port > Port::completion || !callback) return E_INVALIDARG;
|
|
const auto queue = acquire_queue(handle);
|
|
if (!queue) return E_HANDLE;
|
|
auto task = std::unique_ptr<Task>(new (std::nothrow) CallbackTask(callback, context));
|
|
if (!task) return E_OUTOFMEMORY;
|
|
// delay_ms == 0 is due now, which is the common case and matches the old
|
|
// immediate-submit behaviour. A nonzero delay is a GetTickCount64 deadline.
|
|
task->due_ms = delay_ms == 0 ? 0 : GetTickCount64() + delay_ms;
|
|
return submit(queue, port, std::move(task)) ? S_OK : E_HANDLE;
|
|
}
|
|
|
|
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void** out) {
|
|
if (!out) return false;
|
|
*out = nullptr;
|
|
const auto queue = acquire_queue(nullptr);
|
|
if (!queue) return false;
|
|
try {
|
|
std::lock_guard lock(queues_mutex);
|
|
*out = add_handle(queue);
|
|
return true;
|
|
} catch (const std::bad_alloc&) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
} // extern "C"
|