diff options
author | Thiago Marcos P. Santos <thiago@mapbox.com> | 2015-07-14 17:01:20 +0300 |
---|---|---|
committer | Thiago Marcos P. Santos <thiago@mapbox.com> | 2015-07-16 19:38:35 +0300 |
commit | 7d500e9330eaf096fdbe89e33b1bf00526873e0e (patch) | |
tree | 9c5773fd6994c0b21c6c4bfcf98dca68d3c02fd4 /src | |
parent | 70aea89e131125b3d92fcc99c5b3ecd1e148d0c8 (diff) | |
download | qtlocation-mapboxgl-7d500e9330eaf096fdbe89e33b1bf00526873e0e.tar.gz |
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.
Diffstat (limited to 'src')
-rw-r--r-- | src/mbgl/util/work_queue.cpp | 37 | ||||
-rw-r--r-- | src/mbgl/util/work_queue.hpp | 36 |
2 files changed, 73 insertions, 0 deletions
diff --git a/src/mbgl/util/work_queue.cpp b/src/mbgl/util/work_queue.cpp new file mode 100644 index 0000000000..7e1406bba0 --- /dev/null +++ b/src/mbgl/util/work_queue.cpp @@ -0,0 +1,37 @@ +#include <mbgl/util/work_queue.hpp> + +#include <mbgl/util/run_loop.hpp> + +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<void()>&& fn) { + std::lock_guard<std::mutex> 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<void()>& fn) { + assert(runLoop == RunLoop::Get()); + + fn(); + + std::lock_guard<std::mutex> 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 0000000000..dcec5668b9 --- /dev/null +++ b/src/mbgl/util/work_queue.hpp @@ -0,0 +1,36 @@ +#ifndef MBGL_UTIL_WORK_QUEUE +#define MBGL_UTIL_WORK_QUEUE + +#include <mbgl/util/noncopyable.hpp> +#include <mbgl/util/work_request.hpp> + +#include <functional> +#include <memory> +#include <mutex> +#include <queue> + +namespace mbgl { +namespace util { + +class RunLoop; + +class WorkQueue : private util::noncopyable { +public: + WorkQueue(); + virtual ~WorkQueue(); + + void push(std::function<void()>&&); + +private: + void pop(const std::function<void()>&); + + std::queue<std::unique_ptr<WorkRequest>> queue; + std::mutex queueMutex; + + RunLoop* runLoop; +}; + +} +} + +#endif |