|
Boost : |
From: Andrey Semashev (andysem_at_[hidden])
Date: 2007-01-06 18:29:11
Hello Steven,
Sunday, January 7, 2007, 2:02:10 AM, you wrote:
> AMDG
> Andrey Semashev wrote:
>> This is just wrong. It is perfectly legal
>> > for the compiler to reorder it to be
>> > if (!m_fInitialized)
>> > {
>> > m_fInitialized = true;
>> > // Fill m_StatesInfo array for all states
>> > const root_type* pRoot = pStates;
>> > pStates->__init_states_info(reinterpret_cast< const char*
>> >>(pRoot), m_StatesInfo);
>>
>>> > }
>>> > then
>>> > Thread A
>>> > if (!m_fInitialized)
>>> > {
>>> > m_fInitialized = true;
>>> > Thread B
>>> > if (!m_fInitialized)
>>> > {
>>> > }
>>> > //use m_StatesInfo.
>>> > //die.
>>>
>> I'd rather say, your scenario is possible here but not necessarily it
>> will happen. A compiler _may_ be smart enough to reorder expressions
>> if it may prove that it won't break the code behavior (which is true
>> here) and it will gain something (performance, for example) from it.
>> And even if it does so consider that Thread A in your example may be
>> interleaved by Thread B right between it checks "m_fInitialized" and
>> stores "true" in it. So it is actually possible that more than one
>> thread will execute the "true" branch of the "if" statement
>> concurrently. But we're on the safe side here because only simple
>> operations on POD types are involved in it.
> I see that it is ok for m_StatesInfo to be initialized more than once.
> My point was
> that it can be used before it is initialized unless you make everything
> involved volatile.
Oh, you're right. But isn't it enough just to mark "m_fInitialized" as
"volatile"? According to 1.9/7 it would enforce the compiler to
initialize "m_StatesInfo" prior to setting "m_fInitialized".
-- Best regards, Andrey mailto:andysem_at_[hidden]
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk