Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > Programming Threads > Re: POD functio...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 3 Topic 4070 of 4146
Post > Topic >>

Re: POD function static initialization from function return, thread safe?

by Anthony Williams <anthony.ajw@[EMAIL PROTECTED] > Oct 6, 2008 at 02:19 PM

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
 




 3 Posts in Topic:
POD function static initialization from function return, thread
Brian Cole <coleb2@[EM  2008-10-04 14:50:23 
Re: POD function static initialization from function return, thr
David Schwartz <davids  2008-10-06 04:57:25 
Re: POD function static initialization from function return, thr
Anthony Williams <anth  2008-10-06 14:19:19 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sat Nov 22 9:05:00 CST 2008.