|
Boost Users : |
Subject: Re: [Boost-users] [thread] boost::call_once() optimization idea on Win32
From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2010-11-19 00:33:32
On Thu, Nov 18, 2010 at 5:50 AM, Thomas Jarosch
<thomas.jarosch_at_[hidden]> wrote:
> Hello Tony,
>
>
> Thanks for the detailed explanation! As you pointed out, the second thread
> will mess up without the barrier. Time to fix my code :)
>
> One more small thing: IMHO the write reordering in the first
> thread can't happen because of the memory barrier created
> by interlockedExchange(). The first thread translates to this:
>
Yes, of course. Sorry, I removed that interlock as well in my
example, since that question also often comes up, so I was basically
just giving my standard explanation. I should have been more clear.
>
> Let me illustrate it a bit more:
>
..
> Don't we need an interlocked read here, too?
>
> Or does the mutex/memory barrier ensure the compiler
> isn't allowed to do register caching?
>
Technically, since C++ still doesn't know anything about threads,
there could be some register caching. But there isn't, because the
compiler writers and thread packages work this all out for us, using
whatever non-standard calls or extensions that are required.
There are some papers out there such as "Threads cannot be done in a
library" by Boehm
http://www.stanford.edu/class/cs240/readings/p261-boehm.pdf going into
more detail about this. In particular, exotic cases such as:
if (some_condition)
lock(mutex);
for (i = 0; i < N; i++)
{
do_stuff();
if (some_condition)
x++;
}
if (some_condition)
unlock(mutex);
So the programmer's intent is that x is only updated sometimes, and
that happens to be the only time that the mutex is needed.
This is a case that, without being careful, compilers can optimize
incorrectly. C++0x will take care of these cases.
But beyond some exotic cases with aggresive optimizations, normal
mutexes with non-volatiles just works. And I don't think volatiles
fixes the cases listed in the paper.
>
> Nice! Too bad "www.boostcon.com" currently issues
> a "500 - Internal Server Error" :o)
!
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