"Fossies" - the Fresh Open Source Software Archive

Member "cutter-1.8.2/src/common/AsyncTask.cpp" (20 May 2019, 1476 Bytes) of package /linux/privat/cutter-1.8.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "AsyncTask.cpp" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 1.8.0_vs_1.8.1.

    1 
    2 #include "AsyncTask.h"
    3 
    4 AsyncTask::AsyncTask()
    5     : QObject(nullptr),
    6       QRunnable()
    7 {
    8     setAutoDelete(false);
    9     running = false;
   10 }
   11 
   12 AsyncTask::~AsyncTask()
   13 {
   14     wait();
   15 }
   16 
   17 void AsyncTask::wait()
   18 {
   19     runningMutex.lock();
   20     runningMutex.unlock();
   21 }
   22 
   23 bool AsyncTask::wait(int timeout)
   24 {
   25     bool r = runningMutex.tryLock(timeout);
   26     if (r) {
   27         runningMutex.unlock();
   28     }
   29     return r;
   30 }
   31 
   32 void AsyncTask::interrupt()
   33 {
   34     interrupted = true;
   35 }
   36 
   37 void AsyncTask::prepareRun()
   38 {
   39     interrupted = false;
   40     wait();
   41     timer.start();
   42 }
   43 
   44 void AsyncTask::run()
   45 {
   46     runningMutex.lock();
   47 
   48     running = true;
   49 
   50     logBuffer.clear();
   51     emit logChanged(logBuffer);
   52     runTask();
   53 
   54     running = false;
   55 
   56     emit finished();
   57 
   58     runningMutex.unlock();
   59 }
   60 
   61 void AsyncTask::log(QString s)
   62 {
   63     logBuffer += s.append(QLatin1Char('\n'));
   64     emit logChanged(logBuffer);
   65 }
   66 
   67 AsyncTaskManager::AsyncTaskManager(QObject *parent)
   68     : QObject(parent)
   69 {
   70     threadPool = new QThreadPool(this);
   71 }
   72 
   73 AsyncTaskManager::~AsyncTaskManager()
   74 {
   75 }
   76 
   77 void AsyncTaskManager::start(AsyncTask::Ptr task)
   78 {
   79     tasks.append(task);
   80     task->prepareRun();
   81 
   82     QWeakPointer<AsyncTask> weakPtr = task;
   83     connect(task.data(), &AsyncTask::finished, this, [this, weakPtr]() {
   84         tasks.removeOne(weakPtr);
   85         emit tasksChanged();
   86     });
   87     threadPool->start(task.data());
   88     emit tasksChanged();
   89 }
   90 
   91 bool AsyncTaskManager::getTasksRunning()
   92 {
   93     return !tasks.isEmpty();
   94 }