How to test my blocking queue actually blocks

I have a blocking queue (it would be very difficult for me to change its implementation), and I want to check that it actually blocks. In particular, methods popshould block if the queue is empty and unlock as soon as it is executed push. See the following pseudo-C ++ 11 code for a test:

BlockingQueue queue; // empty queue

thread pushThread([] 
{ 
    sleep(large_delay);
    queue.push(); 
});

queue.pop();

Obviously, this is not ideal, because it can happen that the entire thread pushThreadexecutes and terminates before it is called pop, even if the delay is large, and the longer the delay, the more I have to wait for the test to end.

How can I correctly verify that it popis executed before it pushis called and will be blocked until pushit returns?

+4
3

, BlockingQueue.

. , pop. , pop. , , pop.

100% - , - , , "- ". pop . push , "- ". , .

, , , , ... - , , " " - , , - . .

, , .

+1
template<class T>
struct async_queue {
  T pop() {
    auto l = lock();
    ++wait_count;
    cv.wait( l, [&]{ return !data.empty(); } );
    --wait_count;
    auto r = std::move(data.front());
    data.pop_front();
    return r;
  }
  void push(T in) {
    {
      auto l = lock();
      data.push_back( std::move(in) );
    }
    cv.notify_one();
  }
  void push_many(std::initializer_list<T> in) {
    {
      auto l = lock();
      for (auto&& x: in) 
        data.push_back( x );
    }
    cv.notify_all();
  }
  std::size_t readers_waiting() {
    return wait_count;
  }
  std::size_t data_waiting() const {
    auto l = lock();
    return data.size();
  }
private:
  std::queue<T> data;
  std::condition_variable cv;
  mutable std::mutex m;
  std::atomic<std::size_t> wait_count{0};
  auto lock() const { return std::unique_lock<std::mutex>(m); }

};

somesuch.

readers_waiting , 1.

cv.wait, . push.

cv.wait - , push, ...

, , ..

readers_waiting data_waiting , , .

+1

You can use std::condition_variableto accomplish this. The cppreference.com man page actually shows a very nice example of a comumer manufacturer, which should be exactly what you are looking for: http://en.cppreference.com/w/cpp/thread/condition_variable

EDIT: Actually in the German version of cppreference.com there is an even better example :-) http://de.cppreference.com/w/cpp/thread/condition_variable

0
source

Source: https://habr.com/ru/post/1689462/


All Articles