summaryrefslogtreecommitdiff
path: root/src/mbgl/util/thread_pool.cpp
blob: 040e996dd47d504680990c891ed9dcd2c57bf5b4 (plain)
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
#include <mbgl/util/thread_pool.hpp>

#include <mbgl/util/platform.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/platform/thread.hpp>

namespace mbgl {

ThreadedSchedulerBase::~ThreadedSchedulerBase() = default;

void ThreadedSchedulerBase::terminate() {
    {
        std::lock_guard<std::mutex> lock(mutex);
        terminated = true;
    }
    cv.notify_all();
}

std::thread ThreadedSchedulerBase::makeSchedulerThread(size_t index) {
    return std::thread([this, index]() {
        platform::setCurrentThreadName(std::string{"Worker "} + util::toString(index + 1));
        platform::attachThread();

        while (true) {
            std::unique_lock<std::mutex> lock(mutex);

            cv.wait(lock, [this] { return !queue.empty() || terminated; });

            if (terminated) {
                platform::detachThread();
                return;
            }

            auto function = std::move(queue.front());
            queue.pop();
            lock.unlock();
            if (function) function();
        }
    });
}

void ThreadedSchedulerBase::schedule(std::function<void()> fn) {
    assert(fn);
    {
        std::lock_guard<std::mutex> lock(mutex);
        queue.push(std::move(fn));
    }

    cv.notify_one();
}

} // namespace mbgl