You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
MoneroDaemonService/src/FutureScheduler.cpp

97 lines
2.2 KiB

// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2014-2021, The Monero Project.
#include "FutureScheduler.h"
FutureScheduler::FutureScheduler(QObject *parent)
: QObject(parent), Alive(0), Stopping(false)
{
static std::once_flag once;
std::call_once(once, []() {
QThreadPool::globalInstance()->setMaxThreadCount(4);
});
}
FutureScheduler::~FutureScheduler()
{
shutdownWaitForFinished();
}
void FutureScheduler::shutdownWaitForFinished() noexcept
{
QMutexLocker locker(&Mutex);
Stopping = true;
while (Alive > 0)
{
Condition.wait(&Mutex);
}
}
QPair<bool, QFuture<void>> FutureScheduler::run(std::function<void()> function) noexcept
{
return execute<void>([this, function](QFutureWatcher<void> *) {
return QtConcurrent::run([this, function] {
try
{
function();
}
catch (const std::exception &exception)
{
qWarning() << "Exception thrown from async function: " << exception.what();
}
done();
});
});
}
QPair<bool, QFuture<QVariantList>> FutureScheduler::run(std::function<QVariantList()> function, const std::function<void(QVariantList)> callback)
{
return execute<QVariantList>([this, function, callback](QFutureWatcher<QVariantList> *watcher) {
connect(watcher, &QFutureWatcher<QVariantList>::finished, [watcher, callback] {
callback(watcher->future().result());
});
return QtConcurrent::run([this, function] {
QVariantList result;
try
{
result = function();
}
catch (const std::exception &exception)
{
qWarning() << "Exception thrown from async function: " << exception.what();
}
done();
return result;
});
});
}
bool FutureScheduler::stopping() const noexcept
{
return Stopping;
}
bool FutureScheduler::add() noexcept
{
QMutexLocker locker(&Mutex);
if (Stopping)
{
return false;
}
++Alive;
return true;
}
void FutureScheduler::done() noexcept
{
{
QMutexLocker locker(&Mutex);
--Alive;
}
Condition.wakeAll();
}