|
Boost Users : |
Subject: Re: [Boost-users] Condition Variable and optimization
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2011-12-15 13:56:11
AMDG
On 12/15/2011 10:29 AM, John M. Dlugosz wrote:
> The example in the documentation for Condition Variables illustrates the
> implication that these are Mesa-style (non-blocking signals) with this
> example:
>
cond.wait() does block, but spurious wakeups
are allowed, hence the loop.
> 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();
> }
>
>
>
> This needs to declare data_ready as mutable, so the compiler doesn't
> reduce the while loop to a no-op and assume the value doesn't change, or
> just hold it in a register so it doesn't see the change made by another
> thread.
>
> More generally, how do you write it in this case?
>
> while ( !collection.empty() ) cond.wait(lock);
>
> where the condition is a function of an existing class? The compiler
> might inline that function and give the same issue.
>
If the compiler doesn't know anything about
condition variables, it will see an opaque
function call that can potentially clobber
any non-local variables. If the compiler
does know about condition variables, then
it knows that it can't optimize like this.
> I think a form of wait that takes a predicate ought to be introduced,
> that prevents this particular issue and ensures correct use.
>
It already exists.
In Christ,
Steven Watanabe
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