Brian Cole <coleb2@[EMAIL PROTECTED]
> writes:
> I know from previous posts on this list that function static
> initialization is not thread safe. But in the case of initializing
> plain old data (POD) from a re-entrant function that will return the
> same value every time, the race condition appears to be
> inconsequential. The assumption appears to be that POD assignment is
> atomic, isn't this true on all major platforms?
POD assignment in general is not atomic unless
sizeof(POD)==sizeof(int), even on platforms where plain ops on an int
are atomic (e.g. x86).
The lack of atomicity of the assignment is the only problem with
static initialization and threads.
> For example:
> unsigned int Bar(); // a threadsafe function that always returns the
> same value
> void Foo()
> {
> static unsigned int bar = Bar();
> // go on to make use of bar
> }
>
> Is this assumption safe? Where is it not? Or am I just playing with
> fire and asking to get burned?
This is not guaranteed to be safe prior to C++0x. If multiple threads
call Foo() concurrently, more than one may call Bar(). You've said
that Bar() is thread-safe so that in itself isn't a problem other than
performance-wise. However, it's not the only issue. The flag to
indicate that bar is correctly initialized cannot be assumed to be
thread-safe, or have any visibility guarantees, so other threads may
see the flag set before the new value of bar has been stored, and thus
read the uninitialized value of bar.
Anthony
--
Anthony Williams | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL


|