File: TaskManager.cpp

package info (click to toggle)
openterface-qt 0.1.0%2Bds-1
  • links: PTS
  • area: main
  • in suites: experimental
  • size: 1,444 kB
  • sloc: cpp: 9,552; sh: 127; python: 57; ansic: 4; makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,307 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "TaskManager.h"

TaskManager* TaskManager::instance()
{
    static TaskManager instance;
    return &instance;
}

TaskManager::TaskManager() : m_worker(new Worker()), m_workerThread()
{
    m_worker->moveToThread(&m_workerThread);
    connect(&m_workerThread, &QThread::started, m_worker, &Worker::onProcessTasks);
    m_workerThread.start();
}

TaskManager::~TaskManager()
{
    {
        QMutexLocker locker(&m_worker->m_mutex);
        m_worker->m_exit = true;
    }
    m_worker->m_condition.wakeOne();
    m_workerThread.quit();
    m_workerThread.wait();
    delete m_worker;
}

void TaskManager::addTask(std::function<void()> task)
{
    {
        QMutexLocker locker(&m_worker->m_mutex);
        m_worker->m_taskQueue.enqueue(task);
    }
    m_worker->m_condition.wakeOne();
}

TaskManager::Worker::Worker() : m_exit(false)
{
}

TaskManager::Worker::~Worker()
{
}

void TaskManager::Worker::onProcessTasks()
{
    while (!m_exit) {
        std::function<void()> task;
        {
            QMutexLocker locker(&m_mutex);
            if (m_taskQueue.isEmpty()) {
                m_condition.wait(&m_mutex);
            }
            if (!m_taskQueue.isEmpty()) {
                task = m_taskQueue.dequeue();
            }
        }
        if (task) {
            task();
        }
    }
}