[Interest] Heavily Commented Example: Simple Single Frontend with Two Backends

Bo Thorsen bo at fioniasoftware.dk
Mon Oct 22 14:16:33 CEST 2012


Den 22-10-2012 12:10, Jan Kundrát skrev:
> 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.

In general, no. For all x86 and x86-64 processors, it is true. Ints and 
bools have atomic reads and writes on those platforms.

>   Declaring a variable volatile does *not* make it suitable to be
> used as a synchronization primitive across threads. As a side effect, it
> might also make the code run slower.
>
> According to my understanding, the reason for this is the C++ memory
> model (or lack thereof); while volatile might look like a great way to
> force an "always load stuff from memory" approach, it does not impose a
> particular ordering of the read/write operations, so the
> compiler/CPU/memory controller/... are actually allowed to reorder
> access to other memory regions (and they really do that). That's not
> what you want to do.

Not correct. Neither the compiler nor the CPU can reorder around a volatile.

You are correct that it's slower than a normal bool/int. But if it's 
only used as a flag across threads, it's *much* faster than any kind of 
protected region.

The reason it's slower is that nothing can be optimized with volatiles. 
For example, this code:

volatile bool b;
// ...
b = true;
if (b) ...

The executed code has to write the true to the actual memory pointed to 
by b and read it back from that in the if statement just after it. 
Another thread could have changed it between the two statements. So no 
register or cache can be used to speed this up and the compiler won't 
optimize the check away.

This does of course work. Otherwise, volatiles would be useless.

Bo Thorsen.

Come by my DevDays talk in Berlin - "Designing for testability". Learn how to build and run your unit tests with the Qt application.

Fionia Software - Qt experts for hire.




More information about the Interest mailing list