cameron314 / concurrentqueue

A fast multi-producer, multi-consumer lock-free concurrent queue for C++11
Other
9.53k stars 1.66k forks source link

wait_dequeue_bulk_timed success but there no data dequeued #321

Closed pengweichu closed 1 year ago

pengweichu commented 1 year ago

Hi again, I have the below code that I can get the wait_dequeue_bulk_timed returned correctly size, but the v is empty. Could you please point where is wrong?

BlockingConcurrentqueue<std::unique_ptr<AgentInfo>, Traits> mQueue;

std::vector<std::unique_ptr<AgentInfo>> v;
 v.reserve(16);

  while (!mShutdown)
  {  
    auto vsize = mQueue.wait_dequeue_bulk_timed(v.begin(), 16, std::chrono::milliseconds(100));
  // **the visize is greater than 0, but the v is empty.**

    auto vsize = mQueue.wait_dequeue_bulk_timed(std::make_move_iterator(v.begin()), 16, std::chrono::milliseconds(100));
  // **the visize is greater than 0, but the v is empty.**
}

It's works good with the array or std::array, can't I use it with vector?

std::unique_ptr<AgentInfo> v[16];
auto vsize = mQueue.wait_dequeue_bulk_timed(v, 16, std::chrono::milliseconds(100));
cameron314 commented 1 year ago

You're passing in an iterator to an empty vector. The queue will therefore write past the end of the vector (technically undefined behaviour despite the reserve).

Either resize the vector first, or use a back inserter:

v.resize(16);
v.resize(mQueue.wait_dequeue_bulk(v.begin(), v.size()));

mQueue.wait_dequeue_bulk(std::back_inserter(v), 16);
pengweichu commented 1 year ago

thanks, that works good.