Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <mutex>
- #include <condition_variable>
- #include <chrono>
- #include <map>
- template <class T>
- class TimerQueue {
- public:
- using Clock = std::chrono::system_clock;
- using TimePoint = Clock::time_point;
- public:
- void Add(const T& item, TimePoint at) {
- std::unique_lock<std::mutex> lock(mtx_); // Останавливается здесь
- data_.insert({item, at});
- }
- T Pop() {
- std::unique_lock<std::mutex> lock(mtx_);
- TimePoint wait_time = data_.begin()->second;
- T value = data_.begin()->first;
- for (auto& [k, v] : data_) {
- if (v < wait_time) {
- wait_time = std::min(wait_time, v);
- value = k;
- }
- }
- data_.erase(data_.find(value));
- cv_.wait_until(lock, wait_time);
- return value;
- }
- private:
- std::multimap<T, TimePoint> data_;
- std::condition_variable cv_;
- std::mutex mtx_;
- };
- // Тест
- TEST(TimerQueue, TwoThreads) {
- auto now = Now();
- TimerQueue<int> queue;
- std::atomic<bool> finished = false;
- std::thread worker([&] {
- queue.Pop();
- finished = true;
- });
- std::this_thread::sleep_for(500ms);
- EXPECT_FALSE(finished);
- queue.Add(0, now);
- worker.join();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement