|
Boost Users : |
Subject: Re: [Boost-users] [thread] variables in thread examples require 'volatile'?
From: Cory Nelson (phrosty_at_[hidden])
Date: 2009-12-08 02:48:21
On Mon, Dec 7, 2009 at 7:16 PM, Stonewall Ballard <sb.list_at_[hidden]> wrote:
>
> On Dec 7, 2009, at 7:56 PM, Steven Watanabe wrote:
>
>> AMDG
>>
>> Gabriel Redner wrote:
>>> I'm involved in a bit of a dispute in which a colleague is claiming
>>> that 'volatile' is necessary to make certain synchronization patterns
>>> correct. Â As part of my response I pointed out that the boost.thread
>>> examples don't use it, but he maintains his position - saying that the
>>> examples are flawed. Â I'm frankly somewhat out of my element here, and
>>> I'd like to get input from people who have presumably thought about
>>> this stuff a good deal.
>>>
>>> The example in question is here, under "synopsis":
>>> http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref
>>>
>>> The claim is that 'volatile' is needed on the boolean, otherwise the
>>> compiler might cache the boolean in a register, and the loop would
>>> never exit. Â He cites for support two articles:
>>>
>>> http://www.ddj.com/cpp/184403766
>>> https://www.securecoding.cert.org/confluence/display/seccode/DCL17-C.+Beware+of+miscompiled+volatile-qualified+variables
>>>
>>> Who's right?
>>>
>>
>> volatile is not needed in that example because access is protected by a mutex.
>>
>
> In this example:
> ----
> boost::condition_variable cond;
> boost::mutex mut;
> bool data_ready;
>
> void process_data();
>
> void wait_for_data_to_process()
> {
> Â Â boost::unique_lock<boost::mutex> lock(mut);
> Â Â while(!data_ready)
> Â Â {
> Â Â Â Â cond.wait(lock);
> Â Â }
> Â Â process_data();
> }
> ----
>
> What prevents the compiler from leaving data_ready in a register while in the while loop, hence never seeing some other thread setting it? The mutex is released while waiting on the condition, so data_ready is not protected while in cond.wait().
There are a few things it could be doing so that it could look like
that and still be correct:
a) An explicit barrier intrinsic, which is a more optimal way to get
volatile semantics. (ie. VC++'s _ReadWriteBarrier)
b) An atomic intrinsic which the compiler recognizes as an implicit
barrier. (ie. VC++'s _InterlockedCompareExchange)
c) A function with unknown side effects is being called somewhere.
(ie. anything the compiler doesn't have a full definition of... like
an operating system's own mutex functions)
-- Cory Nelson http://int64.org
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net