diff options
Diffstat (limited to 'src/mbgl/util/thread_pool.cpp')
-rw-r--r-- | src/mbgl/util/thread_pool.cpp | 63 |
1 files changed, 27 insertions, 36 deletions
diff --git a/src/mbgl/util/thread_pool.cpp b/src/mbgl/util/thread_pool.cpp index e839d1b4be..040e996dd4 100644 --- a/src/mbgl/util/thread_pool.cpp +++ b/src/mbgl/util/thread_pool.cpp @@ -6,53 +6,44 @@ namespace mbgl { -ThreadPool::ThreadPool(std::size_t count) { - threads.reserve(count); +ThreadedSchedulerBase::~ThreadedSchedulerBase() = default; - for (std::size_t i = 0; i < count; ++i) { - threads.emplace_back([this, i]() { - platform::setCurrentThreadName(std::string{ "Worker " } + util::toString(i + 1)); - platform::attachThread(); - - while (true) { - std::unique_lock<std::mutex> lock(mutex); +void ThreadedSchedulerBase::terminate() { + { + std::lock_guard<std::mutex> lock(mutex); + terminated = true; + } + cv.notify_all(); +} - cv.wait(lock, [this] { - return !queue.empty() || terminate; - }); +std::thread ThreadedSchedulerBase::makeSchedulerThread(size_t index) { + return std::thread([this, index]() { + platform::setCurrentThreadName(std::string{"Worker "} + util::toString(index + 1)); + platform::attachThread(); - if (terminate) { - platform::detachThread(); - return; - } + while (true) { + std::unique_lock<std::mutex> lock(mutex); - auto mailbox = queue.front(); - queue.pop(); - lock.unlock(); + cv.wait(lock, [this] { return !queue.empty() || terminated; }); - Mailbox::maybeReceive(mailbox); + if (terminated) { + platform::detachThread(); + return; } - }); - } -} -ThreadPool::~ThreadPool() { - { - std::lock_guard<std::mutex> lock(mutex); - terminate = true; - } - - cv.notify_all(); - - for (auto& thread : threads) { - thread.join(); - } + auto function = std::move(queue.front()); + queue.pop(); + lock.unlock(); + if (function) function(); + } + }); } -void ThreadPool::schedule(std::weak_ptr<Mailbox> mailbox) { +void ThreadedSchedulerBase::schedule(std::function<void()> fn) { + assert(fn); { std::lock_guard<std::mutex> lock(mutex); - queue.push(mailbox); + queue.push(std::move(fn)); } cv.notify_one(); |