1
0
mirror of https://github.com/TomHarte/CLK.git synced 2024-11-25 16:31:42 +00:00
CLK/Concurrency/AsyncUpdater.hpp

100 lines
2.4 KiB
C++
Raw Normal View History

//
// AsyncUpdater.h
// Clock Signal
//
// Created by Thomas Harte on 06/07/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef AsyncUpdater_hpp
#define AsyncUpdater_hpp
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "../ClockReceiver/TimeTypes.hpp"
namespace Concurrency {
template <typename Performer> class AsyncUpdater {
public:
2022-07-07 15:10:54 +00:00
template <typename... Args> AsyncUpdater(Args&&... args) :
performer(std::forward<Args>(args)...),
2022-07-07 15:10:54 +00:00
actions_(std::make_unique<ActionVector>()),
performer_thread_{
[this] {
Time::Nanos last_fired = Time::nanos_now();
2022-07-07 15:10:54 +00:00
auto actions = std::make_unique<ActionVector>();
while(!should_quit) {
2022-07-07 15:10:54 +00:00
// Wait for new actions to be signalled, and grab them.
std::unique_lock lock(condition_mutex_);
while(actions_->empty()) {
condition_.wait(lock);
}
2022-07-07 15:10:54 +00:00
std::swap(actions, actions_);
lock.unlock();
// Update to now.
auto time_now = Time::nanos_now();
performer.perform(time_now - last_fired);
last_fired = time_now;
2022-07-07 15:10:54 +00:00
// Perform the actions.
for(const auto& action: *actions) {
action();
}
actions->clear();
}
}
} {}
/// Run the performer up to 'now' and then perform @c post_action.
///
/// @c post_action will be performed asynchronously, on the same
/// thread as the performer.
2022-07-07 15:10:54 +00:00
///
/// Actions may be elided,
void update(const std::function<void(void)> &post_action) {
std::lock_guard guard(condition_mutex_);
2022-07-07 15:10:54 +00:00
actions_->push_back(post_action);
condition_.notify_all();
}
2022-07-07 20:56:10 +00:00
void stop() {
if(performer_thread_.joinable()) {
should_quit = true;
update([] {});
performer_thread_.join();
}
}
~AsyncUpdater() {
2022-07-07 20:56:10 +00:00
stop();
}
2022-07-07 15:10:54 +00:00
// The object that will actually receive time advances.
Performer performer;
private:
2022-07-07 15:10:54 +00:00
// The list of actions waiting be performed. These will be elided,
// increasing their latency, if the emulation thread falls behind.
using ActionVector = std::vector<std::function<void(void)>>;
std::unique_ptr<ActionVector> actions_;
// Necessary synchronisation parts.
2022-07-08 00:09:37 +00:00
std::atomic<bool> should_quit = false;
std::mutex condition_mutex_;
std::condition_variable condition_;
2022-07-08 00:09:37 +00:00
// Ensure the thread isn't constructed until after the mutex
// and condition variable.
std::thread performer_thread_;
};
}
#endif /* AsyncUpdater_hpp */