POD function static initialization from function return, thread safe?

POD function static initialization from function return, thread safe?

Post by Anthony Wi » Thu, 09 Oct 2008 16:13:53


Brian Cole < XXXX@XXXXX.COM > writes:


That isn't even guaranteed to compile prior to C++0x and the POSIX C++
binding currently in progress.


This will work with POSIX/C++0x.


You need extra braces

#define MUTEX_INIT {PTHREAD_MUTEX_INITIALIZER}


Yes, this is safe. Compilers must ensure that
initialization of a static pthread_mutex_t with
PTHREAD_MUTEX_INITIALIZER is done in a thread-safe manner.

Anthony
--
Anthony Williams | Just Software Solutions Ltd
Custom Software Development | http://www.yqcomputer.com/
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL
 
 
 

POD function static initialization from function return, thread safe?

Post by Anthony Wi » Thu, 09 Oct 2008 16:18:27

David Schwartz < XXXX@XXXXX.COM > writes:



A single-threaded program can't tell the difference because C doesn't
have dynamic initialization or destructors. The same sentence is in
C90, so therefore applies to POSIX, which supports threads. A
multithreaded program could therefore tell the difference if the
compiler just did naive "initialization on first use" without
synchronization. Since the whole point of the question is "can I rely
on such initialization being thread-safe", the answer is "YES"
(otherwise the compiler has violated the quoted statement, even under
the as-if rule), and it doesn't matter how it achieves that.

Anthony
--
Anthony Williams | Just Software Solutions Ltd
Custom Software Development | http://www.yqcomputer.com/
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL