summaryrefslogtreecommitdiff
path: root/src/mbgl/util/worker.cpp
blob: ad26ea5b18afe4135480c934fb62a32e9c8b8978 (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
#include <mbgl/util/worker.hpp>
#include <mbgl/platform/platform.hpp>

#include <cassert>
#include <future>

namespace mbgl {

class Worker::Impl {
public:
    Impl(uv_loop_t*) {}

    void doWork(std::packaged_task<void ()>& task) {
        task();
    }
};

Worker::Worker(std::size_t count) {
    for (std::size_t i = 0; i < count; i++) {
        threads.emplace_back(util::make_unique<util::Thread<Impl>>("Worker", util::ThreadPriority::Low));
    }
}

Worker::~Worker() = default;

WorkRequest Worker::send(Fn work, Fn after) {
    std::packaged_task<void ()> task(work);
    std::future<void> future = task.get_future();

    std::shared_ptr<std::atomic<bool>> joined = std::make_shared<std::atomic<bool>>();
    *joined = false;

    threads[current]->invokeWithResult(&Worker::Impl::doWork, [joined, after] {
        if (!*joined) {
            after();
        }
    }, task);

    current = (current + 1) % threads.size();
    return WorkRequest(std::move(future), joined);
}

}