Re: Thread and C++
On Mar 31, 3:58 am, peter koch <peter.koch.lar...@gmail.com> wrote:
On 30 Mar., 22:16, Ioannis Vranos <ivra...@freemail.gr> wrote:
The stopped variable is declared volatile because it is accessed from d=
ifferent threads and we want to be sure
that it is freshly read every time it is needed. If we omitted the vola=
tile keyword, the compiler might
optimize access to the variable, possibly leading to incorrect results"=
..
That is clearly wrong: if the boolean "stopped" is modified using a
mutex only, there is no need for the volatile. What might happen is
that stopped is not modified under the control of a mutex: if the only
change that might take place is a change from false to true, it is my
understanding that such a change will be safe. And even if there might
be perverted situations where this might not be the case, I am
confident that no implementation ever would behave like that.
If we assume that stopped is accessed without using a mutex, it is
possible that the value written by one thread will never propagate to
another. The problem just is that this will not change with volatile.
I've seen a bool marked volatile cause a problem until it had a mutex
controlling access to it. It was pretty rare, maybe one time 50,000
write/reads.
I think the problem comes down to cache coherency -- the volatile may
force a memory read, but there doesn't seem to be any guarantee of
cache write throughs or cache coherency. You'd have to check the
compiler documentation for what it says, or more likely the code
produced to see what it really does.
K