| 1 | #include <mbgl/util/default_thread_pool.hpp> |
|---|---|
| 2 | #include <mbgl/actor/mailbox.hpp> |
| 3 | #include <mbgl/util/platform.hpp> |
| 4 | #include <mbgl/util/string.hpp> |
| 5 | |
| 6 | namespace mbgl { |
| 7 | |
| 8 | ThreadPool::ThreadPool(std::size_t count) { |
| 9 | threads.reserve(n: count); |
| 10 | for (std::size_t i = 0; i < count; ++i) { |
| 11 | threads.emplace_back(args: [this, i]() { |
| 12 | platform::setCurrentThreadName(std::string{ "Worker "} + util::toString(t: i + 1)); |
| 13 | |
| 14 | while (true) { |
| 15 | std::unique_lock<std::mutex> lock(mutex); |
| 16 | |
| 17 | cv.wait(lock&: lock, p: [this] { |
| 18 | return !queue.empty() || terminate; |
| 19 | }); |
| 20 | |
| 21 | if (terminate) { |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | auto mailbox = queue.front(); |
| 26 | queue.pop(); |
| 27 | lock.unlock(); |
| 28 | |
| 29 | Mailbox::maybeReceive(mailbox); |
| 30 | } |
| 31 | }); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | ThreadPool::~ThreadPool() { |
| 36 | { |
| 37 | std::lock_guard<std::mutex> lock(mutex); |
| 38 | terminate = true; |
| 39 | } |
| 40 | |
| 41 | cv.notify_all(); |
| 42 | |
| 43 | for (auto& thread : threads) { |
| 44 | thread.join(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | void ThreadPool::schedule(std::weak_ptr<Mailbox> mailbox) { |
| 49 | { |
| 50 | std::lock_guard<std::mutex> lock(mutex); |
| 51 | queue.push(x: mailbox); |
| 52 | } |
| 53 | |
| 54 | cv.notify_one(); |
| 55 | } |
| 56 | |
| 57 | } // namespace mbgl |
| 58 |
