From 78696cb39bbc9e6460c7d77fb9949fe2516ae4dd Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 26 Feb 2018 16:52:20 +0100 Subject: Make the Id class thread-safe When copying it over from Qt Creator, we forgot to adapt it to a non- threadsafe environment. Change-Id: I83c3dd47627fe01a67042d71b897427f5a7adf2b Reviewed-by: Joerg Bornemann --- src/lib/corelib/tools/id.cpp | 34 +++++++++++++--------------------- src/lib/corelib/tools/id.h | 1 - 2 files changed, 13 insertions(+), 22 deletions(-) diff --git a/src/lib/corelib/tools/id.cpp b/src/lib/corelib/tools/id.cpp index 66c5f85d7..1c61792e6 100644 --- a/src/lib/corelib/tools/id.cpp +++ b/src/lib/corelib/tools/id.cpp @@ -43,6 +43,7 @@ #include #include +#include #include namespace qbs { @@ -117,11 +118,19 @@ static int firstUnusedId = Id::IdsPerPlugin * Id::ReservedPlugins; static QHash stringFromId; static IdCache idFromString; +static std::mutex mutex; + +static QByteArray getStringFromId(int id) +{ + std::lock_guard lock(mutex); + return stringFromId.value(id).str; +} static int theId(const char *str, int n = 0) { QBS_ASSERT(str && *str, return 0); StringHolder sh(str, n); + std::lock_guard lock(mutex); int res = idFromString.value(sh, 0); if (res == 0) { res = firstUnusedId++; @@ -178,7 +187,7 @@ Id::Id(const QByteArray &name) QByteArray Id::name() const { - return stringFromId.value(m_id).str; + return getStringFromId(m_id); } /*! @@ -193,7 +202,7 @@ QByteArray Id::name() const QString Id::toString() const { - return QString::fromUtf8(stringFromId.value(m_id).str); + return QString::fromUtf8(getStringFromId(m_id)); } /*! @@ -205,7 +214,7 @@ QString Id::toString() const QVariant Id::toSetting() const { - return QVariant(QString::fromUtf8(stringFromId.value(m_id).str)); + return QVariant(QString::fromUtf8(getStringFromId(m_id))); } /*! @@ -260,26 +269,9 @@ Id Id::withPrefix(const char *prefix) const return Id(ba.constData()); } - -/*! - Associates a id with its uid and its string - representation. - - The uid should be taken from the plugin's private range. - - \sa fromSetting() -*/ - -void Id::registerId(int uid, const char *name) -{ - StringHolder sh(name, 0); - idFromString[sh] = uid; - stringFromId[uid] = sh; -} - bool Id::operator==(const char *name) const { - const char *string = stringFromId.value(m_id).str; + const char *string = getStringFromId(m_id); if (string && name) return strcmp(string, name) == 0; else diff --git a/src/lib/corelib/tools/id.h b/src/lib/corelib/tools/id.h index aedecd66e..f0c3b1588 100644 --- a/src/lib/corelib/tools/id.h +++ b/src/lib/corelib/tools/id.h @@ -77,7 +77,6 @@ public: int uniqueIdentifier() const { return m_id; } static Id fromUniqueIdentifier(int uid) { return Id(uid); } static Id fromSetting(const QVariant &variant); // Good to use. - static void registerId(int uid, const char *name); private: // Intentionally unimplemented -- cgit v1.2.1