diff --git a/.clang-format b/.clang-format index 109b562b5..ff0f39e73 100644 --- a/.clang-format +++ b/.clang-format @@ -2,7 +2,7 @@ Standard: Cpp11 IndentWidth: 4 AccessModifierOffset: -4 UseTab: Never -BinPackParameters: true +BinPackParameters: false AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AllowShortBlocksOnASingleLine: false @@ -10,7 +10,7 @@ AllowShortFunctionsOnASingleLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: true AlwaysBreakTemplateDeclarations: true NamespaceIndentation: None -PointerBindsToType: false +PointerBindsToType: true SpacesInParentheses: false BreakBeforeBraces: Attach ColumnLimit: 100 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/include/mbgl/platform/log.hpp b/include/mbgl/platform/log.hpp index de7f13171..5d287eb57 100644 --- a/include/mbgl/platform/log.hpp +++ b/include/mbgl/platform/log.hpp @@ -68,7 +68,7 @@ private: // This method is the data sink that must be implemented by each platform we // support. It should ideally output the error message in a human readable // format to the developer. - static void platformRecord(EventSeverity severity, Event event, int64_t code, const std::string &msg); + static void platformRecord(EventSeverity severity, const std::string &msg); }; } diff --git a/platform/android/log_android.cpp b/platform/android/log_android.cpp index 9de8232ba..e5c8cfd81 100644 --- a/platform/android/log_android.cpp +++ b/platform/android/log_android.cpp @@ -1,8 +1,5 @@ #include -#define __STDC_FORMAT_MACROS // NDK bug workaround: https://code.google.com/p/android/issues/detail?id=72349 -#include - #include namespace mbgl { @@ -30,8 +27,8 @@ int severityToPriority(EventSeverity severity) { } // namespace -void Log::platformRecord(EventSeverity severity, Event event, int64_t code, const std::string &msg) { - __android_log_print(severityToPriority(severity), EventClass(event).c_str(), "(%" PRId64 ") %s", code, msg.c_str()); +void Log::platformRecord(EventSeverity severity, const std::string &msg) { + __android_log_print(severityToPriority(severity), "mbgl", "%s", msg.c_str()); } } diff --git a/platform/darwin/log_nslog.mm b/platform/darwin/log_nslog.mm index 5d53ed812..a2e31968a 100644 --- a/platform/darwin/log_nslog.mm +++ b/platform/darwin/log_nslog.mm @@ -4,12 +4,10 @@ namespace mbgl { -void Log::platformRecord(EventSeverity severity, Event event, int64_t code, - const std::string &msg) { +void Log::platformRecord(EventSeverity severity, const std::string &msg) { NSString *message = [[NSString alloc] initWithBytes:msg.data() length:msg.size() encoding:NSUTF8StringEncoding]; - NSLog(@"[%s] %s: (%lld) %@", EventSeverityClass(severity).c_str(), EventClass(event).c_str(), - code, message); + NSLog(@"[%s] %@", EventSeverityClass(severity).c_str(), message); } } diff --git a/platform/default/log_stderr.cpp b/platform/default/log_stderr.cpp index 3305176d9..f7ef34184 100644 --- a/platform/default/log_stderr.cpp +++ b/platform/default/log_stderr.cpp @@ -4,8 +4,8 @@ namespace mbgl { -void Log::platformRecord(EventSeverity severity, Event event, int64_t code, const std::string &msg) { - std::cerr << "[" << severity << "] " << event << ": (" << code << ") " << msg << std::endl; +void Log::platformRecord(EventSeverity severity, const std::string &msg) { + std::cerr << "[" << severity << "] " << msg << std::endl; } } diff --git a/src/mbgl/map/environment.cpp b/src/mbgl/map/environment.cpp index ee13d33ea..1aea5aa0c 100644 --- a/src/mbgl/map/environment.cpp +++ b/src/mbgl/map/environment.cpp @@ -3,32 +3,129 @@ #include +#include #include +#include +#include namespace mbgl { -Environment::Environment(FileSource &fs) : fileSource(fs), loop(uv_loop_new()) { +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; +}; + +unsigned makeEnvironmentID() { + static std::atomic id(0); + return id++; } -void Environment::setup() { - mapThread = std::this_thread::get_id(); +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); } -bool Environment::inMapThread() const { - return std::this_thread::get_id() == mapThread; +Environment::Scope::~Scope() { + assert(id == std::this_thread::get_id()); + threadInfoStore.unregisterThread(); } -void Environment::requestAsync(const Resource &resource, std::function callback) { +Environment::Environment(FileSource& fs) + : id(makeEnvironmentID()), 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; +} + +unsigned Environment::getID() const { + return id; +} + +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()); +Request* Environment::request(const Resource& resource, + std::function callback) { + assert(currentlyOn(ThreadType::Map)); return fileSource.request(resource, loop, *this, std::move(callback)); } -void Environment::cancelRequest(Request *req) { - assert(inMapThread()); +void Environment::cancelRequest(Request* req) { + assert(currentlyOn(ThreadType::Map)); fileSource.cancel(req); } diff --git a/src/mbgl/map/environment.hpp b/src/mbgl/map/environment.hpp index b68a7b9e2..b631abf13 100644 --- a/src/mbgl/map/environment.hpp +++ b/src/mbgl/map/environment.hpp @@ -16,27 +16,45 @@ class Request; class Response; struct Resource; -class Environment : private util::noncopyable { +enum class ThreadType : uint8_t { + Unknown = 0, + Main = 1 << 0, + Map = 1 << 1, + TileWorker = 1 << 2, +}; + +class Environment final : private util::noncopyable { public: - Environment(FileSource &); + class Scope final { + public: + Scope(Environment&, ThreadType, const std::string& name); + ~Scope(); - void setup(); + private: + std::thread::id id; + }; - bool inMapThread() const; + Environment(FileSource&); - void requestAsync(const Resource &, std::function); - Request *request(const Resource &, std::function); - void cancelRequest(Request *); + static Environment& Get(); + static bool inScope(); + static bool currentlyOn(ThreadType); + static std::string threadName(); + + unsigned getID() const; + void requestAsync(const Resource&, std::function); + Request* request(const Resource&, std::function); + void cancelRequest(Request*); // Request to terminate the environment. void terminate(); private: - FileSource &fileSource; - std::thread::id mapThread; + unsigned id; + FileSource& fileSource; public: - uv_loop_t *const loop; + uv_loop_t* const loop; }; } diff --git a/src/mbgl/map/live_tile_data.cpp b/src/mbgl/map/live_tile_data.cpp index 92777f67f..192efb7dc 100644 --- a/src/mbgl/map/live_tile_data.cpp +++ b/src/mbgl/map/live_tile_data.cpp @@ -15,10 +15,9 @@ LiveTileData::LiveTileData(Tile::ID const& id_, GlyphStore& glyphStore_, SpriteAtlas& spriteAtlas_, util::ptr sprite_, - const SourceInfo& source_, - Environment& env_) + const SourceInfo& source_) : VectorTileData::VectorTileData(id_, mapMaxZoom, style_, glyphAtlas_, glyphStore_, - spriteAtlas_, sprite_, source_, env_), + spriteAtlas_, sprite_, source_), annotationManager(annotationManager_) { // live features are always ready state = State::loaded; diff --git a/src/mbgl/map/live_tile_data.hpp b/src/mbgl/map/live_tile_data.hpp index 6b9d0a047..7874d6ff5 100644 --- a/src/mbgl/map/live_tile_data.hpp +++ b/src/mbgl/map/live_tile_data.hpp @@ -17,8 +17,7 @@ public: GlyphStore&, SpriteAtlas&, util::ptr, - const SourceInfo&, - Environment&); + const SourceInfo&); ~LiveTileData(); void parse() override; diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index 2dea2deac..22e6cbceb 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, + source->source->update(*this, 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