From b52aab5f7c6625b219a68cc7a956cf895d158139 Mon Sep 17 00:00:00 2001 From: "Thiago Marcos P. Santos" Date: Fri, 13 Mar 2015 14:22:09 +0200 Subject: [PATCH 1/5] Introduce the ThreadInfoStore and Environment::Scope The Environment will now keep track of every thread that is running within a Environment::Scope. Once the Scope object is created, it will automatically register the thread to the ThreadInfoStore with some additional information and it will automatically deregister as the stack frame rewinds (which can be useful for Threads that are temporally in use by an Environment like Workers). The ThreadInfoStore could be using the thread-local storage, but I think that making the Environment aware of what threads are associated to it can be useful for writing a mechanism for posting messages between threads. Withing a Scope, the Environment associated to the thread can be queried at any time which will save us from juggling a reference to the Environemnt around. Finally, the type of thread (Main, Map, etc) can also be queried at any moment to make sure a piece of code is running on the desired thread. --- src/mbgl/map/environment.cpp | 92 ++++++++++++++++++++++++++++++++++++ src/mbgl/map/environment.hpp | 23 ++++++++- 2 files changed, 113 insertions(+), 2 deletions(-) diff --git a/src/mbgl/map/environment.cpp b/src/mbgl/map/environment.cpp index ee13d33ea..251954327 100644 --- a/src/mbgl/map/environment.cpp +++ b/src/mbgl/map/environment.cpp @@ -4,12 +4,104 @@ #include #include +#include +#include namespace mbgl { +namespace { + +class ThreadInfoStore { +private: + struct ThreadInfo { + Environment* env; + ThreadType type; + std::string name; + }; + +public: + ThreadInfoStore() { + registerThread(nullptr, ThreadType::Main, "Main"); + } + + ~ThreadInfoStore() { + unregisterThread(); + assert(threadSet.size() == 0); + } + + void registerThread(Environment* env, ThreadType type, const std::string& name) { + std::lock_guard lock(mtx); + + // FIXME: We should never need to overwrite a thread here and we only allow + // this today because on the Static mode, the Map thread and the Main thread + // are same. Replace this with emplace() when this gets fixed. + threadSet[std::this_thread::get_id()] = ThreadInfo{env, type, name}; + } + + void unregisterThread() { + std::lock_guard lock(mtx); + + ThreadSet::iterator it = threadSet.find(std::this_thread::get_id()); + if (it != threadSet.end()) { + threadSet.erase(it); + } + } + + const ThreadInfo& getThreadInfo() const { + static ThreadInfo emptyInfo; + std::lock_guard lock(mtx); + + ThreadSet::const_iterator it = threadSet.find(std::this_thread::get_id()); + if (it != threadSet.end()) { + return it->second; + } else { + return emptyInfo; + } + } + +private: + typedef std::unordered_map ThreadSet; + ThreadSet threadSet; + + mutable std::mutex mtx; +}; + +ThreadInfoStore threadInfoStore; + +} // namespace + +Environment::Scope::Scope(Environment& env, ThreadType type, const std::string& name) + : id(std::this_thread::get_id()) { + threadInfoStore.registerThread(&env, type, name); +} + +Environment::Scope::~Scope() { + assert(id == std::this_thread::get_id()); + threadInfoStore.unregisterThread(); +} + Environment::Environment(FileSource &fs) : fileSource(fs), loop(uv_loop_new()) { } +Environment& Environment::Get() { + Environment* env = threadInfoStore.getThreadInfo().env; + assert(env); + + return *env; +} + +bool Environment::inScope() { + return threadInfoStore.getThreadInfo().env; +} + +bool Environment::currentlyOn(ThreadType type) { + return static_cast(threadInfoStore.getThreadInfo().type) & static_cast(type); +} + +std::string Environment::threadName() { + return threadInfoStore.getThreadInfo().name; +} + void Environment::setup() { mapThread = std::this_thread::get_id(); } diff --git a/src/mbgl/map/environment.hpp b/src/mbgl/map/environment.hpp index b68a7b9e2..86d40cc38 100644 --- a/src/mbgl/map/environment.hpp +++ b/src/mbgl/map/environment.hpp @@ -16,10 +16,30 @@ class Request; class Response; struct Resource; -class Environment : private util::noncopyable { +enum class ThreadType : uint8_t { + Unknown = 0, + Main = 1 << 0, + Map = 1 << 1, +}; + +class Environment final : private util::noncopyable { public: + class Scope final { + public: + Scope(Environment&, ThreadType, const std::string& name); + ~Scope(); + + private: + std::thread::id id; + }; + Environment(FileSource &); + static Environment& Get(); + static bool inScope(); + static bool currentlyOn(ThreadType); + static std::string threadName(); + void setup(); bool inMapThread() const; @@ -33,7 +53,6 @@ public: private: FileSource &fileSource; - std::thread::id mapThread; public: uv_loop_t *const loop; From b5facd35bc766e32e00ebfccc8ea0721f243373a Mon Sep 17 00:00:00 2001 From: "Thiago Marcos P. Santos" Date: Fri, 13 Mar 2015 15:03:33 +0200 Subject: [PATCH 2/5] Scope the Map thread to an Environment Also, replace manual thread type checks with Environment::currentlyOn(). --- include/mbgl/map/map.hpp | 3 -- src/mbgl/map/environment.cpp | 12 +----- src/mbgl/map/environment.hpp | 4 -- src/mbgl/map/map.cpp | 75 ++++++++++++++++-------------------- 4 files changed, 35 insertions(+), 59 deletions(-) diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index b03217570..86c89f769 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -217,9 +217,6 @@ private: // Stores whether the map thread has been stopped already. std::atomic_bool isStopped; - const std::thread::id mainThread; - std::thread::id mapThread; - Transform transform; TransformState state; diff --git a/src/mbgl/map/environment.cpp b/src/mbgl/map/environment.cpp index 251954327..98cf2d353 100644 --- a/src/mbgl/map/environment.cpp +++ b/src/mbgl/map/environment.cpp @@ -102,25 +102,17 @@ std::string Environment::threadName() { return threadInfoStore.getThreadInfo().name; } -void Environment::setup() { - mapThread = std::this_thread::get_id(); -} - -bool Environment::inMapThread() const { - return std::this_thread::get_id() == mapThread; -} - void Environment::requestAsync(const Resource &resource, std::function callback) { fileSource.request(resource, *this, std::move(callback)); } Request *Environment::request(const Resource &resource, std::function callback) { - assert(inMapThread()); + assert(currentlyOn(ThreadType::Map)); return fileSource.request(resource, loop, *this, std::move(callback)); } void Environment::cancelRequest(Request *req) { - assert(inMapThread()); + assert(currentlyOn(ThreadType::Map)); fileSource.cancel(req); } diff --git a/src/mbgl/map/environment.hpp b/src/mbgl/map/environment.hpp index 86d40cc38..97813d358 100644 --- a/src/mbgl/map/environment.hpp +++ b/src/mbgl/map/environment.hpp @@ -40,10 +40,6 @@ public: static bool currentlyOn(ThreadType); static std::string threadName(); - void setup(); - - bool inMapThread() const; - void requestAsync(const Resource &, std::function); Request *request(const Resource &, std::function); void cancelRequest(Request *); diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index 2dea2deac..7af3b54de 100644 --- a/src/mbgl/map/map.cpp +++ b/src/mbgl/map/map.cpp @@ -62,8 +62,6 @@ using namespace mbgl; Map::Map(View& view_, FileSource& fileSource_) : env(util::make_unique(fileSource_)), view(view_), - mainThread(std::this_thread::get_id()), - mapThread(mainThread), transform(view_), fileSource(fileSource_), glyphAtlas(util::make_unique(1024, 1024)), @@ -99,7 +97,7 @@ uv::worker &Map::getWorker() { } void Map::start(bool startPaused) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); assert(mode == Mode::None); // When starting map rendering in another thread, we perform async/continuously @@ -111,7 +109,7 @@ void Map::start(bool startPaused) { // Setup async notifications asyncTerminate = util::make_unique(env->loop, [this]() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); // Remove all of these to make sure they are destructed in the correct thread. style.reset(); @@ -127,7 +125,7 @@ void Map::start(bool startPaused) { }); asyncUpdate = util::make_unique(env->loop, [this] { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); if (state.hasSize()) { prepare(); @@ -136,7 +134,7 @@ void Map::start(bool startPaused) { asyncRender = util::make_unique(env->loop, [this] { // Must be called in Map thread. - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); render(); @@ -154,20 +152,12 @@ void Map::start(bool startPaused) { } thread = std::thread([this]() { -#ifdef DEBUG - mapThread = std::this_thread::get_id(); -#endif - #ifdef __APPLE__ pthread_setname_np("Map"); #endif run(); -#ifdef DEBUG - mapThread = std::thread::id(); -#endif - // Make sure that the stop() function knows when to stop invoking the callback function. isStopped = true; view.notify(); @@ -175,8 +165,7 @@ void Map::start(bool startPaused) { } void Map::stop(std::function callback) { - assert(std::this_thread::get_id() == mainThread); - assert(mainThread != mapThread); + assert(Environment::currentlyOn(ThreadType::Main)); assert(mode == Mode::Continuous); asyncTerminate->send(); @@ -203,7 +192,7 @@ void Map::stop(std::function callback) { } void Map::pause(bool waitForPause) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); assert(mode == Mode::Continuous); mutexRun.lock(); pausing = true; @@ -221,7 +210,7 @@ void Map::pause(bool waitForPause) { } void Map::resume() { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); assert(mode == Mode::Continuous); mutexRun.lock(); @@ -231,13 +220,20 @@ void Map::resume() { } void Map::run() { + ThreadType threadType = ThreadType::Map; + std::string threadName("Map"); + if (mode == Mode::None) { -#ifdef DEBUG - mapThread = mainThread; -#endif mode = Mode::Static; + + // FIXME: Threads should have only one purpose. When running on Static mode, + // we are currently not spawning a Map thread and running the code on the + // Main thread, thus, the Main thread in this case is both Main and Map thread. + threadType = static_cast(static_cast(threadType) | static_cast(ThreadType::Main)); + threadName += "andMain"; } - assert(std::this_thread::get_id() == mapThread); + + Environment::Scope scope(*env, threadType, threadName); if (mode == Mode::Continuous) { checkForPause(); @@ -251,8 +247,6 @@ void Map::run() { workers = util::make_unique(env->loop, 4, "Tile Worker"); - env->setup(); - setup(); prepare(); @@ -273,9 +267,6 @@ void Map::run() { // *after* all events have been processed. if (mode == Mode::Static) { render(); -#ifdef DEBUG - mapThread = std::thread::id(); -#endif mode = Mode::None; } @@ -284,7 +275,7 @@ void Map::run() { void Map::renderSync() { // Must be called in UI thread. - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); triggerRender(); @@ -335,7 +326,7 @@ void Map::terminate() { #pragma mark - Setup void Map::setup() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); assert(painter); painter->setup(); } @@ -541,42 +532,42 @@ const std::string &Map::getAccessToken() const { #pragma mark - Annotations void Map::setDefaultPointAnnotationSymbol(std::string& symbol) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); annotationManager->setDefaultPointAnnotationSymbol(symbol); } uint32_t Map::addPointAnnotation(LatLng point, std::string& symbol) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); std::vector points({ point }); std::vector symbols({ symbol }); return addPointAnnotations(points, symbols)[0]; } std::vector Map::addPointAnnotations(std::vector points, std::vector& symbols) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); auto result = annotationManager->addPointAnnotations(points, symbols, *this); updateAnnotationTiles(result.first); return result.second; } void Map::removeAnnotation(uint32_t annotation) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); removeAnnotations({ annotation }); } void Map::removeAnnotations(std::vector annotations) { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); auto result = annotationManager->removeAnnotations(annotations); updateAnnotationTiles(result); } std::vector Map::getAnnotationsInBounds(LatLngBounds bounds) const { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); return annotationManager->getAnnotationsInBounds(bounds, *this); } LatLngBounds Map::getBoundsForAnnotations(std::vector annotations) const { - assert(std::this_thread::get_id() == mainThread); + assert(Environment::currentlyOn(ThreadType::Main)); return annotationManager->getBoundsForAnnotations(annotations); } @@ -658,7 +649,7 @@ std::chrono::steady_clock::duration Map::getDefaultTransitionDuration() { } void Map::updateSources() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); // First, disable all existing sources. for (const auto& source : activeSources) { @@ -687,7 +678,7 @@ void Map::updateSources() { } void Map::updateSources(const util::ptr &group) { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); if (!group) { return; } @@ -701,18 +692,18 @@ void Map::updateSources(const util::ptr &group) { } void Map::updateTiles() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); for (const auto &source : activeSources) { source->source->update(*this, *env, getWorker(), style, *glyphAtlas, *glyphStore, *spriteAtlas, getSprite(), *texturePool, [this]() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); triggerUpdate(); }); } } void Map::prepare() { - assert(std::this_thread::get_id() == mapThread); + assert(Environment::currentlyOn(ThreadType::Map)); if (!style) { style = std::make_shared