diff options
author | Thiago Marcos P. Santos <tmpsantos@gmail.com> | 2017-05-26 13:54:43 -0300 |
---|---|---|
committer | Ivo van Dongen <info@ivovandongen.nl> | 2017-05-30 13:42:46 +0300 |
commit | 1a6c6ea19746245b9492efaaba464d8a653062e8 (patch) | |
tree | 5609cd696dd6c5cef41cb9ce2082a38aa3775b37 | |
parent | 4198f176145443f7d2ad93eebd317dbc04f5cabb (diff) | |
download | qtlocation-mapboxgl-1a6c6ea19746245b9492efaaba464d8a653062e8.tar.gz |
[core] Added the ThreadedRunLoop
Actor model version of util::Thread.
-rw-r--r-- | platform/default/mbgl/util/threaded_run_loop.cpp | 45 | ||||
-rw-r--r-- | platform/default/mbgl/util/threaded_run_loop.hpp | 31 |
2 files changed, 76 insertions, 0 deletions
diff --git a/platform/default/mbgl/util/threaded_run_loop.cpp b/platform/default/mbgl/util/threaded_run_loop.cpp new file mode 100644 index 0000000000..e27e6379b6 --- /dev/null +++ b/platform/default/mbgl/util/threaded_run_loop.cpp @@ -0,0 +1,45 @@ +#include <mbgl/actor/mailbox.hpp> +#include <mbgl/util/platform.hpp> +#include <mbgl/util/run_loop.hpp> +#include <mbgl/util/threaded_run_loop.hpp> + +namespace mbgl { + +ThreadedRunLoop::ThreadedRunLoop(const std::string& name) + : thread([&]() { + platform::setCurrentThreadName(name); + + loop = std::make_unique<util::RunLoop>(util::RunLoop::Type::New); + running.set_value(); + + loop->run(); + loop.reset(); + }) { + running.get_future(); +} + +ThreadedRunLoop::~ThreadedRunLoop() { + loop->stop(); + thread.join(); +} + +void ThreadedRunLoop::schedule(std::weak_ptr<Mailbox> mailbox) { + { + std::lock_guard<std::mutex> lock(mutex); + queue.push(mailbox); + } + + loop->invoke([this] { receive(); }); +} + +void ThreadedRunLoop::receive() { + std::unique_lock<std::mutex> lock(mutex); + + auto mailbox = queue.front(); + queue.pop(); + lock.unlock(); + + Mailbox::maybeReceive(mailbox); +} + +} // namespace mbgl diff --git a/platform/default/mbgl/util/threaded_run_loop.hpp b/platform/default/mbgl/util/threaded_run_loop.hpp new file mode 100644 index 0000000000..f7f9fcfd65 --- /dev/null +++ b/platform/default/mbgl/util/threaded_run_loop.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include <mbgl/actor/scheduler.hpp> + +#include <future> +#include <memory> +#include <mutex> +#include <queue> +#include <string> +#include <thread> + +namespace mbgl { + +class ThreadedRunLoop : public Scheduler { +public: + ThreadedRunLoop(const std::string& name); + ~ThreadedRunLoop() override; + + void schedule(std::weak_ptr<Mailbox>) override; + +private: + void receive(); + + std::mutex mutex; + std::promise<void> running; + std::queue<std::weak_ptr<Mailbox>> queue; + std::thread thread; + std::unique_ptr<util::RunLoop> loop; +}; + +} // namespace mbgl |