[core] Introduce SequencedScheduler and ParallelScheduler

This commit refactors `utils::ThreadPool` into a template
`ThreadedScheduler` class and provides aux type aliases.
So that it is possible to obtain a sequenced schedule,where
all the scheduled tasks are guarantied to be executed
consequently.

The sequenced lightweight scheduler is required by both the
orchestration thread and the refactored `FileSource` implementation.
This commit is contained in:
Mikhail Pozdnyakov
2019-10-07 15:45:45 +03:00
parent bd283fc1be
commit 23cebe20fe
3 changed files with 75 additions and 44 deletions

View File

@@ -6,49 +6,41 @@
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);
cv.wait(lock, [this] {
return !queue.empty() || terminate;
});
if (terminate) {
platform::detachThread();
return;
}
auto function = std::move(queue.front());
queue.pop();
lock.unlock();
if (function) function();
}
});
}
}
ThreadPool::~ThreadPool() {
void ThreadedSchedulerBase::terminate() {
{
std::lock_guard<std::mutex> lock(mutex);
terminate = true;
terminated = true;
}
cv.notify_all();
for (auto& thread : threads) {
thread.join();
}
}
void ThreadPool::schedule(std::function<void()> fn) {
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));