1
0
mirror of https://github.com/TomHarte/CLK.git synced 2024-06-30 22:29:56 +00:00
CLK/OSBindings/Qt/timer.cpp
Thomas Harte f7e13356c4 FunctionThreads no longer automatically start.
Improvements as a result: audio works in a second machine started in an existing window; there is no audio thread footprint if there is no audio.
2020-07-01 18:55:42 -04:00

44 lines
1.1 KiB
C++

#include "timer.h"
#include "../../ClockReceiver/TimeTypes.hpp"
#include <algorithm>
#include <QDebug>
Timer::Timer(QObject *parent) : QObject(parent) {}
void Timer::startWithMachine(MachineTypes::TimedMachine *machine, std::mutex *machineMutex) {
this->machine = machine;
this->machineMutex = machineMutex;
thread.start();
thread.performAsync([this] {
// Set up the emulation timer. Bluffer's guide: the QTimer will post an
// event to an event loop. QThread is a thread with an event loop.
// My class, Timer, will be wired up to receive the QTimer's events.
timer = std::make_unique<QTimer>();
timer->setInterval(1);
connect(timer.get(), &QTimer::timeout, this, &Timer::tick, Qt::DirectConnection);
timer->start();
});
}
void Timer::tick() {
const auto now = Time::nanos_now();
const auto duration = std::min(now - lastTickNanos, int64_t(500'000'000));
lastTickNanos = now;
std::lock_guard lock_guard(*machineMutex);
machine->run_for(double(duration) / 1e9);
}
Timer::~Timer() {
thread.performAsync([this] {
if(timer) {
timer->stop();
}
});
thread.stop();
}