SPMC_Queue icon indicating copy to clipboard operation
SPMC_Queue copied to clipboard

`write_idx` Overflow issue?

Open plum7ree opened this issue 9 months ago • 0 comments

Nice code. But I have a question about the next_idx. What happens next_idx get overflowed into 0? The read() will always return null?

    T* read() {
      auto& blk = q->blks[next_idx % CNT];
      uint32_t new_idx = ((std::atomic<uint32_t>*)&blk.idx)->load(std::memory_order_acquire);
      if (int(new_idx - next_idx) < 0) return nullptr; // <---- here. 
      next_idx = new_idx + 1;
      return &blk.data;
    }

  template<typename Writer>
  void write(Writer writer) {
    auto& blk = blks[++write_idx % CNT]; // <----here. what if overflow?
    writer(blk.data);
    ((std::atomic<uint32_t>*)&blk.idx)->store(write_idx, std::memory_order_release); // <----here.  blk.idx = overflowed write_idx = 0
  }


https://github.com/MengRao/SPMC_Queue/blob/master/SPMCQueue.h#L38

plum7ree avatar Sep 19 '23 08:09 plum7ree