Boost logo

Boost Users :

Subject: Re: [Boost-users] circular buffer in a multithreaded program
From: Sebastian Gesemann (s.gesemann_at_[hidden])
Date: 2014-04-24 04:06:49

Hi Steffen,

On Thu, Apr 24, 2014 at 9:47 AM, Steffen Heil (Mailinglisten)
<lists_at_[hidden]> wrote:
> This might be a general C++ question and not be boost specific, but as I read the answer above the following question popped up:
> If two threads read / write the same area in the memory and there is no synchronization, how is it ever guaranteed that they see the "current" values?
> I see the problem, if one threads writes to a certain place in a buffer and another thread reads from that buffer, it might read cached values (either by the compiler keeping a value in a register or by the hardware keeping copies in cpu caches while the two threads run in different cpu cores / cpus).
> So any kind of synchronization (that usually involves a memory barrier) is needed...

True. In my case, there is mutex-based synchronization. A reader has
to wait for the writer marking the new values as "ready". This
insovles locking/unlocking a mutex. And I would expect that
locking/unlocking a mutex also involves a kind of "memory barrier"
which should solve the cache issues.

> Coming from java there is a memory model that clearly specifies a "happens-before" relation. Values are guaranteed to be available if the operations in place are ordered according to that relation.
> Is there any C++ specification for these things?
> How much is it compiler / platform specific?

I also programmed in Java. From what I can tell, there is little
difference between Java and C++ in this regard. The terminology is
just different. What you call "monitor", "volatile" and "happens
before" in Java is called "mutex", "amotic" and "sequenced before". On
top of that C++11 allows you to use "weaker synchronization". But
that's something I choose to ignore because it's just too easy to get
it wrong and not worth the performance gain in my opinion.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at