Dequeued item exists but std::counting_semaphore::try_acquire() fails in single-consumer MPSC queue

I have a single-consumer, multiple-producer lock-free queue (MPSCQueue) combined with a std::counting_semaphore to notify the consumer when new items are enqueued. The consumer uses dequeue() to attempt fetching an item; if it succeeds, it calls sema.try_acquire() which I expect to succeed every time there’s actually an item in the queue. However, under very rare circumstances, I get an assertion failure indicating try_acquire() returned false even though the queue returned a valid item.

I can confirm there is truly only one consumer thread. There are no other places calling dequeue(). The code uses std::memory_order_seq_cst for atomic operations in the queue, and sema.release()/sema.acquire() for the semaphore.

Why might this happen?

It seems like a memory ordering or visibility issue where the consumer sees the newly linked node in the queue before it sees the corresponding release() operation on the semaphore. But I thought seq_cst plus semaphore release/acquire would be enough to guarantee proper ordering. Any ideas or clarifications on how to ensure we never see a valid item in the queue but still fail try_acquire()?

#include <atomic>
#include <cassert>
#include <iostream>
#include <optional>
#include <semaphore>

template <typename T>
class MPSCQueue {
  struct Node {
    T data;
    std::atomic<Node*> next;

    // Default constructor for the dummy node
    Node() : next(nullptr) {}
    // Constructor that moves the data in
    Node(T data_) : data(std::move(data_)), next(nullptr) {}
  };

  // Atomic head pointer for multiple producers
  std::atomic<Node*> head;
  // Tail pointer for the single consumer
  Node* tail;

 public:
  std::atomic_size_t enqueue_count = 0;
  size_t dequeue_count = 0;

  MPSCQueue() {
    Node* dummy = new Node();
    head.store(dummy, std::memory_order_seq_cst);
    tail = dummy;
  }

  ~MPSCQueue() {
    Node* node = tail;
    while (node) {
      Node* next = node->next.load(std::memory_order_seq_cst);
      delete node;
      node = next;
    }
  }

  // Called by producers
  void enqueue(T data) {
    enqueue_count.fetch_add(1);
    Node* node = new Node(std::move(data));
    // Swap in the new node as the head
    Node* prev_head = head.exchange(node, std::memory_order_seq_cst);
    // Link the old head to the new node
    prev_head->next.store(node, std::memory_order_seq_cst);
  }

  // Called by the single consumer
  std::optional<T> dequeue() {
    // Check the next pointer of the tail
    Node* next = tail->next.load(std::memory_order_seq_cst);
    if (next) {
      // Move the data out
      T res = std::move(next->data);
      delete tail;
      tail = next;
      dequeue_count += 1;
      return res;
    }
    return std::nullopt;
  }

  size_t size() { return enqueue_count.load() - dequeue_count; }
};

template <typename T>
class MPSCQueueConsumerLock {
  MPSCQueue<T> queue;
  std::counting_semaphore<> sema{0};

 public:
  void enqueue(T data) {
    queue.enqueue(std::move(data));
    // Release the semaphore to notify the consumer
    sema.release();
  }

  // Single consumer calls this
  T dequeue() {
    auto re = queue.dequeue();
    if (re.has_value()) {
      // We have an item, so we expect the semaphore count to be > 0
      if (!sema.try_acquire()) {
        // Unexpectedly fails in rare cases
        std::cerr << __FILE__ << ":" << __FUNCTION__
                  << " sema.try_acquire() should succeed, please checkn";
        assert(false);
      }
      return re.value();
    }
    // Otherwise, block until something is available
    sema.acquire();
    return queue.dequeue().value();
  }

  size_t size() { return queue.size(); }
};

Symptom

Sometimes (very low probability, but still possible) the code hits:

/path/to/mpsc.hpp:dequeue sema try_acquire should be success, please check
python: /path/to/mpsc.hpp:79: T MPSCQueueConsumerLock<T>::dequeue() [...]
Assertion `false' failed.
Aborted (core dumped)

I have verified there is truly only one consumer thread and this is the only place where dequeue() is called.

Question:

How could it happen that the consumer can see the new node in MPSCQueue, but the corresponding sema.release() call is not observed (so try_acquire() fails)?
Is there a subtlety in std::counting_semaphore or the memory ordering that I’m missing?
Any suggestions to ensure the consumer’s view of the queue and the semaphore’s count stay consistent?

Additional

  • I used std::memory_order_seq_cst for all the atomic operations in the queue.
  • The consumer is strictly single-threaded; no other threads call dequeue().
  • Could there be a hidden memory fence issue between exchange(…, seq_cst) and sema.release()?

Any pointers or advice would be greatly appreciated. Thank you!

New contributor

Ervin Xie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật