From 9bd5e4366e585b439186f1c1486a87dddba6bcbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Konstantin=20K=C3=A4fer?= Date: Tue, 23 Jan 2018 16:59:59 -0800 Subject: [core] prioritize Thread::pause() calls --- include/mbgl/util/run_loop.hpp | 43 ++++++++++++++++++++++++++++++++---------- include/mbgl/util/thread.hpp | 2 +- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/include/mbgl/util/run_loop.hpp b/include/mbgl/util/run_loop.hpp index 7167652687..381e3ae213 100644 --- a/include/mbgl/util/run_loop.hpp +++ b/include/mbgl/util/run_loop.hpp @@ -26,6 +26,11 @@ public: New, }; + enum class Priority : bool { + Default = false, + High = true, + }; + enum class Event : uint8_t { None = 0, Read = 1, @@ -47,11 +52,16 @@ public: void addWatch(int fd, Event, std::function&& callback); void removeWatch(int fd); + // Invoke fn(args...) on this RunLoop. + template + void invoke(Priority priority, Fn&& fn, Args&&... args) { + push(priority, WorkTask::make(std::forward(fn), std::forward(args)...)); + } + // Invoke fn(args...) on this RunLoop. template void invoke(Fn&& fn, Args&&... args) { - std::shared_ptr task = WorkTask::make(std::forward(fn), std::forward(args)...); - push(task); + invoke(Priority::Default, std::forward(fn), std::forward(args)...); } // Post the cancellable work fn(args...) to this RunLoop. @@ -59,7 +69,7 @@ public: std::unique_ptr invokeCancellable(Fn&& fn, Args&&... args) { std::shared_ptr task = WorkTask::make(std::forward(fn), std::forward(args)...); - push(task); + push(Priority::Default, task); return std::make_unique(task); } @@ -80,25 +90,38 @@ private: void wake(); // Adds a WorkTask to the queue, and wakes it up. - void push(std::shared_ptr task) { + void push(Priority priority, std::shared_ptr task) { std::lock_guard lock(mutex); - queue.push(std::move(task)); + if (priority == Priority::High) { + highPriorityQueue.emplace(std::move(task)); + } else { + defaultQueue.emplace(std::move(task)); + } wake(); } void process() { - std::unique_lock lock(mutex); std::shared_ptr task; - while (!queue.empty()) { - task = std::move(queue.front()); - queue.pop(); + std::unique_lock lock(mutex); + while (true) { + if (!highPriorityQueue.empty()) { + task = std::move(highPriorityQueue.front()); + highPriorityQueue.pop(); + } else if (!defaultQueue.empty()) { + task = std::move(defaultQueue.front()); + defaultQueue.pop(); + } else { + break; + } lock.unlock(); (*task)(); + task.reset(); lock.lock(); } } - Queue queue; + Queue defaultQueue; + Queue highPriorityQueue; std::mutex mutex; std::unique_ptr impl; diff --git a/include/mbgl/util/thread.hpp b/include/mbgl/util/thread.hpp index e3bd18143d..74e722b02d 100644 --- a/include/mbgl/util/thread.hpp +++ b/include/mbgl/util/thread.hpp @@ -103,7 +103,7 @@ public: auto pausing = paused->get_future(); - loop->invoke([this] { + loop->invoke(RunLoop::Priority::High, [this] { auto resuming = resumed->get_future(); paused->set_value(); resuming.get(); -- cgit v1.2.1