From 7d500e9330eaf096fdbe89e33b1bf00526873e0e Mon Sep 17 00:00:00 2001 From: "Thiago Marcos P. Santos" Date: Tue, 14 Jul 2015 17:01:20 +0300 Subject: [PATCH] Introduce the WorkQueue The WorkQueue allow other threads to submit tasks to be executed in the thread that the WorkQueue lives on. The WorkQueue will cancel all the pending tasks when it gets destructed, to make sure the tasks won't get called with invalid references. --- src/mbgl/util/work_queue.cpp | 37 ++++++++++++++++++++++++++++++++++++ src/mbgl/util/work_queue.hpp | 36 +++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 src/mbgl/util/work_queue.cpp create mode 100644 src/mbgl/util/work_queue.hpp diff --git a/src/mbgl/util/work_queue.cpp b/src/mbgl/util/work_queue.cpp new file mode 100644 index 000000000..7e1406bba --- /dev/null +++ b/src/mbgl/util/work_queue.cpp @@ -0,0 +1,37 @@ +#include + +#include + +namespace mbgl { +namespace util { + +WorkQueue::WorkQueue() : runLoop(RunLoop::Get()) { +} + +WorkQueue::~WorkQueue() { + assert(runLoop == RunLoop::Get()); + + // Cancel all pending WorkRequests. + while (!queue.empty()) { + queue.pop(); + } +} + +void WorkQueue::push(std::function&& fn) { + std::lock_guard lock(queueMutex); + + auto workRequest = runLoop->invokeCancellable(std::bind(&WorkQueue::pop, this, std::move(fn))); + queue.push(std::move(workRequest)); +} + +void WorkQueue::pop(const std::function& fn) { + assert(runLoop == RunLoop::Get()); + + fn(); + + std::lock_guard lock(queueMutex); + queue.pop(); +} + +} +} diff --git a/src/mbgl/util/work_queue.hpp b/src/mbgl/util/work_queue.hpp new file mode 100644 index 000000000..dcec5668b --- /dev/null +++ b/src/mbgl/util/work_queue.hpp @@ -0,0 +1,36 @@ +#ifndef MBGL_UTIL_WORK_QUEUE +#define MBGL_UTIL_WORK_QUEUE + +#include +#include + +#include +#include +#include +#include + +namespace mbgl { +namespace util { + +class RunLoop; + +class WorkQueue : private util::noncopyable { +public: + WorkQueue(); + virtual ~WorkQueue(); + + void push(std::function&&); + +private: + void pop(const std::function&); + + std::queue> queue; + std::mutex queueMutex; + + RunLoop* runLoop; +}; + +} +} + +#endif