[Interest] Heavily Commented Example: Simple Single Frontend with Two Backends
Till Oliver Knoll
till.oliver.knoll at gmail.com
Mon Oct 22 14:12:15 CEST 2012
2012/10/22 Jan Kundrát <jkt at flaska.net>:
> On 10/22/12 07:21, d3fault wrote:
>> volatile bools work
>
> I wasn't able to find a context for this, but in general, this is not
> true. Declaring a variable volatile does *not* make it suitable to be
> used as a synchronization primitive across threads.
In Academia you'd say "it is not sufficient, but necessary".
Sure, declaring a boolean as "volatile" doesn't make it more
"thread-safe" than when not declaring it as such. But let's have a
look at the following simple usage pattern:
-- header
public:
volatile bool m_continue;
-- implemenation of the "thread body"
void Foo::run()
{
...
m_continue = true;
while (m_continue) {
...
sleep();
}
}
The idea is that the "GUI thread" eventually sets 'm_continue' to
false in order to stop the "worker" thread (for simplicity we assume
that the member 'm_continue' is public). Off course this is totally
not "thread-safe", as the caller could set that member to 'false' just
slightly after the "worker thread" has checked its value.
So the net effect is that the "worker thread" does "one loop too much"
- but /eventually/ it will see that m_continue has been set to 'false'
and will terminate. And that is exactly what we want and hence "good
enough" (no need for protecting the member m_continue with a mutex!).
So what does the "volatile" do? Let's assume a compiler with code
optimisation: such a compiler will see that "Hey! m_continue is set to
'true', but never ever to 'false' inside the following loop! So I am a
smart compiler and do the following optimisation:"
while (true) {
...
sleep();
}
Oopsie! Off course we - the developers - know better than the compiler
(which would not know about another thread possibly modifying that
member). So we tell the compiler: "don't optimise/away/cache the
access to that memory location!" And that's where the "volatile"
modifier enters.
> As a side effect, it
> might also make the code run slower.
Slower as in what? As not declaring it "volatile"? Or slower as "using
a mutex"?
Cheers, Oliver
More information about the Interest
mailing list