2018-05-26 16:21:23 +00:00
|
|
|
|
|
|
|
#include "AsyncTask.h"
|
|
|
|
|
2018-05-26 18:09:20 +00:00
|
|
|
AsyncTask::AsyncTask(QObject *parent)
|
|
|
|
: QObject(parent),
|
|
|
|
QRunnable()
|
|
|
|
{
|
|
|
|
setAutoDelete(false);
|
|
|
|
running = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsyncTask::~AsyncTask()
|
|
|
|
{
|
|
|
|
wait();
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::wait()
|
|
|
|
{
|
|
|
|
runningMutex.lock();
|
|
|
|
runningMutex.unlock();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool AsyncTask::wait(int timeout)
|
|
|
|
{
|
|
|
|
bool r = runningMutex.tryLock(timeout);
|
|
|
|
if (r) {
|
|
|
|
runningMutex.unlock();
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::interrupt()
|
|
|
|
{
|
|
|
|
interrupted = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::prepareRun()
|
|
|
|
{
|
|
|
|
interrupted = false;
|
|
|
|
wait();
|
|
|
|
}
|
|
|
|
|
2018-05-26 16:21:23 +00:00
|
|
|
void AsyncTask::run()
|
|
|
|
{
|
2018-05-26 18:09:20 +00:00
|
|
|
runningMutex.lock();
|
|
|
|
running = true;
|
2018-05-26 16:21:23 +00:00
|
|
|
runTask();
|
|
|
|
emit finished();
|
2018-05-26 18:09:20 +00:00
|
|
|
running = false;
|
|
|
|
runningMutex.unlock();
|
2018-05-26 16:21:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
AsyncTaskManager::AsyncTaskManager(QObject *parent)
|
|
|
|
: QObject(parent)
|
|
|
|
{
|
|
|
|
threadPool = new QThreadPool(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
AsyncTaskManager::~AsyncTaskManager()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTaskManager::start(AsyncTask *task)
|
|
|
|
{
|
2018-05-26 18:09:20 +00:00
|
|
|
task->prepareRun();
|
2018-05-26 16:21:23 +00:00
|
|
|
threadPool->start(task);
|
|
|
|
}
|