|
Boost : |
Subject: Re: [boost] New Book: Introduction to the C++ Boost Libraries, Volume I - Foundations
From: Stewart, Robert (Robert.Stewart_at_[hidden])
Date: 2010-09-22 08:03:08
Daniel J. Duffy wrote:
> > Part: 18.13 Volatile Variables
> >
> > > In order to rectify this situation we declare variables to be volatile
> > > in order to disable register optimisations:
> > >
> > > // Shared variable
> > > volatile int i2;
> > > // The same functions as above but use a volatile variable.
> > > // Not optimised anymore so results are always correct.
> > > void FV1() { while (true) i2++; }
> > > void FV2() { while (true) cout<<i2<<endl; }
> >
> > This is so wrong!
>
> Please explain why this is wrong. Is the code wrong? Is the
> example wrong? Please note that this is a snippet from the full
> test program where two different threads are started to execute
> FV1() and FV2().
volatile affects optimizations but not synchronization. You need
true synchronization for atomicity. C++0x does not reuse
"volatile" to mean atomic because there are still
non-synchronization reasons to declare objects volatile (I/O
ports, for example). Indeed, one can declare a volatile and
atomic object.
> On my dual-core machine the version without volatile produces
> wrong results while the version with volatile produces correct
> results.
That the code happens to work on a particular platform with a
particular toy program does not mean it is correct.
_____
Rob Stewart robert.stewart_at_[hidden]
Software Engineer, Core Software using std::disclaimer;
Susquehanna International Group, LLP http://www.sig.com
IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk