don't do concurrent access to a static member variable

in situations where the renderer is used from multiple threads, this causes memory corruption.

fixes mapbox/node-mapbox-gl-native#7
This commit is contained in:
Konstantin Käfer
2014-10-08 15:27:33 +02:00
parent 36b7bb0c09
commit 91f40daa69
4 changed files with 39 additions and 12 deletions

View File

@@ -1,8 +1,34 @@
#include <mbgl/style/class_dictionary.hpp>
#include <uv.h>
namespace mbgl {
ClassID ClassDictionary::Lookup(const std::string &class_name) {
ClassDictionary::ClassDictionary() {}
ClassDictionary &ClassDictionary::Get() {
// Note: We should eventually switch to uv_key_* functions, but libuv 0.10 doesn't have these
// yet. Instead, we're using the pthread functions directly for now.
static pthread_once_t store_once = PTHREAD_ONCE_INIT;
static pthread_key_t store_key;
// Create the key.
pthread_once(&store_once, []() {
pthread_key_create(&store_key, [](void *ptr) {
delete reinterpret_cast<ClassDictionary *>(ptr);
});
});
ClassDictionary *ptr = reinterpret_cast<ClassDictionary *>(pthread_getspecific(store_key));
if (ptr == nullptr) {
ptr = new ClassDictionary();
pthread_setspecific(store_key, ptr);
}
return *ptr;
}
ClassID ClassDictionary::lookup(const std::string &class_name) {
auto it = store.find(class_name);
if (it == store.end()) {
// Insert the class name into the store.
@@ -14,7 +40,7 @@ ClassID ClassDictionary::Lookup(const std::string &class_name) {
}
}
ClassID ClassDictionary::Normalize(ClassID id) {
ClassID ClassDictionary::normalize(ClassID id) {
if (id >= ClassID::Named) {
return ClassID::Named;
} else {
@@ -22,8 +48,4 @@ ClassID ClassDictionary::Normalize(ClassID id) {
}
}
std::unordered_map<std::string, ClassID> ClassDictionary::store = { { "", ClassID::Default } };
uint32_t ClassDictionary::offset = 0;
}