summaryrefslogtreecommitdiff
path: root/src/mbgl/actor/thread_pool.cpp
blob: 89ca1b72f0b90cfc7b8128637a0d2842a0c60c3b (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
#include <mbgl/actor/thread_pool.hpp>
#include <mbgl/actor/mailbox.hpp>

namespace mbgl {

ThreadPool::ThreadPool(std::size_t count) {
    threads.reserve(count);
    for (std::size_t i = 0; i < count; ++i) {
        threads.emplace_back([this] () {
            while (true) {
                std::unique_lock<std::mutex> lock(mutex);

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

                if (terminate.load()) {
                    return;
                }

                auto mailbox = queue.front();
                queue.pop();
                lock.unlock();

                if (auto locked = mailbox.lock()) {
                    locked->receive();
                }
            }
        });
    }
}

ThreadPool::~ThreadPool() {
    terminate.store(true);
    cv.notify_all();

    for (auto& thread : threads) {
        thread.join();
    }
}

void ThreadPool::schedule(std::weak_ptr<Mailbox> mailbox) {
    std::lock_guard<std::mutex> lock(mutex);
    queue.push(mailbox);
    cv.notify_one();
}

} // namespace mbgl