[Development] Local static variable initialization in multithreaded code

Olivier Goffart olivier at woboq.com
Sun Feb 28 16:37:22 CET 2016


Am Sonntag, 28. Februar 2016, 16:08:44 CET schrieb Vincas Dargis:
> Hello,
> 
> If Qt 5.7 are going to support only "proper" C++11 compilers, can new Qt
> code assume that function local static variable initialization is
> thread-safe?
>
> Qt 5.7 Wiki page [1] makes me think that only Visual Studio 2013 and above
> are supported, is that right? If so, it appears that "magic statics" are
> implemented in 2013 RC [2] .
> 
> So, is it appropriate to write code like this:
> 
> // might be called in multiple threads
> int Foo::bar() {
>      static QAtomicInteger<unsigned int> count;
>      return count.fetchAndAddRelaxed(1);
> }
> 
> I am thinking maybe I could refactor small helper function
> qMakePreparedStmtId() [3] to use QAtomicInteger<unsigned int> instead of
> unsigned int and mutex.

Yes, if every supported compiler have support for it.
But I think it is only working from MSVC 2015. (At least that's how we define 
Q_COMPILER_THREADSAFE_STATICS)
In other words, you cannot use it inconditionaly, but you can use 
#ifdef Q_COMPILER_THREADSAFE_STATICS

But in qMakePreparedStmtId() you can do this inconditionally:

  static QBasicAtomicInt qPreparedStmtCount =  
        Q_BASIC_ATOMIC_INITIALIZER(0);

Since QBasicAtomic is a literal type, it is going to be initialized at compile 
time and can be used without mutexes.


-- 
Olivier 

Woboq - Qt services and support - https://woboq.com - https://code.woboq.org





More information about the Development mailing list