From cbe3791b422728b3ae692009b32836e30c37c9d5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 12 Jan 2023 13:11:17 +0000 Subject: Replace all queues with MPSCQueue where possible --- src/queue.cpp | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) (limited to 'src/queue.cpp') diff --git a/src/queue.cpp b/src/queue.cpp index d3fd69c52..5585b772f 100644 --- a/src/queue.cpp +++ b/src/queue.cpp @@ -10,11 +10,12 @@ struct MPSCNode { // template struct MPSCQueue { + gbAllocator allocator; + std::atomic count; + std::atomic *> head; std::atomic *> tail; - std::atomic count; MPSCNode sentinel; - gbAllocator allocator; }; template gb_internal void mpsc_init (MPSCQueue *q, gbAllocator const &allocator); @@ -29,6 +30,7 @@ gb_internal void mpsc_init(MPSCQueue *q, gbAllocator const &allocator) { q->count.store(0, std::memory_order_relaxed); q->head.store(&q->sentinel, std::memory_order_relaxed); q->tail.store(&q->sentinel, std::memory_order_relaxed); + q->sentinel.next.store(nullptr, std::memory_order_relaxed); } @@ -36,14 +38,20 @@ template gb_internal void mpsc_destroy(MPSCQueue *q) { while (mpsc_dequeue(q, (T *)nullptr)) {} // DO NOTHING for the time being + // free the nodes later } template gb_internal MPSCNode *mpsc_alloc_node(MPSCQueue *q, T const &value) { - auto node = gb_alloc_item(q->allocator, MPSCNode); - node->value = value; - return node; + auto new_node = gb_alloc_item(q->allocator, MPSCNode); + new_node->value = value; + return new_node; +} + +template +gb_internal void mpsc_free_node(MPSCQueue *q, MPSCNode *node) { + // TODO(bill): reuse the free nodes } template @@ -68,10 +76,8 @@ gb_internal bool mpsc_dequeue(MPSCQueue *q, T *value_) { auto next = tail->next.load(std::memory_order_relaxed); if (next) { q->tail.store(next, std::memory_order_relaxed); - // `tail` is now "dead" and needs to be "freed" - tail->value = next->value; - T value = tail->value; - if (value_) *value_ = value; + if (value_) *value_ = next->value; + mpsc_free_node(q, tail); q->count.fetch_sub(1, std::memory_order_acq_rel); return true; } -- cgit v1.2.3