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

Thomas McGuire thomas.mcguire at kdab.com
Mon Oct 22 15:18:17 CEST 2012


On Monday 22 October 2012 14:16:33 Bo Thorsen wrote:
> Den 22-10-2012 12:10, Jan Kundrát skrev:
> > On 10/22/12 07:21, d3fault wrote:

> > 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.

volatile only forces the compiler to create an instruction to fetch the 
variable from memory again, to prevent caching in a register. The CPU doesn't 
even know about the volatile keyword anymore, it just sees a normal fetch 
instruction, and can therefore use the CPU cache.
Therefore, if your two threads are living on different CPUs, one CPU might not 
see the update on the other CPU, since the CPU caches are not updated. 
volatile does not help with that, you need proper memory barriers.

> 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.

It does not work in all cases, see above. volatile _is_ useless for threading, 
its orginal purpose was for memory-mapped IO.

** Qt Developer Conference: http://qtconference.kdab.com/ **

Thomas McGuire | thomas.mcguire at kdab.com | Software Engineer
KDAB (Deutschland) GmbH&Co KG, a KDAB Group company
Tel. Germany +49-30-521325470, Sweden (HQ) +46-563-540090
KDAB - Qt Experts - Platform-independent software solutions
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 3637 bytes
Desc: not available
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20121022/ef7cb3f1/attachment.bin>

More information about the Interest mailing list