std::shared_ptr<T> getNext() { while(true) { std::unique_lock<std::mutex> lock(mutex); condition.wait(lock, [this]() -> bool { return !queue.empty() || isClosed; }); lock.unlock(); if (!queue.empty()) { auto ptr = queue.getMin(); if (ptr) { return ptr; } } if (isClosed) { break; } } return std::shared_ptr<T>(); }
void queue_test() { std::cout << "starting queue test" << std::endl; PriorityQueue<int> queue; const int OPERATIONS_PER_THREAD = 500; const int THREADS_COUNT = 20; auto filler = [&]() { for (size_t index = 0; index < OPERATIONS_PER_THREAD; ++index) { queue.add(index, index); } }; auto getter = [&]() { for (size_t index = 0; index < OPERATIONS_PER_THREAD; ++index) { queue.getMin(); } }; auto worker = [=](std::function<void()> func) { std::vector<boost::thread> threads; for (size_t index = 0; index < THREADS_COUNT; ++index) { threads.emplace_back(func); } for (auto & it : threads) { it.join(); } }; std::cout << "start filling" << std::endl; worker(filler); std::cout << "size after filling: " << queue.size() << std::endl; std::cout << "start getting" << std::endl; worker(getter); std::cout << "size after getting: " << queue.size() << std::endl; std::cout << "done" << std::endl; assert(queue.empty()); }