[LAD] a *simple* ring buffer, comments pls?

Dan Muresan danmbox at gmail.com
Fri Jul 8 19:23:21 UTC 2011


>> > > the one wrinkle in this is that in theory a compiler
>> > > could so completely reorder instructions that even the
>> > > basic assumptions that make the single
>> > > reader/single-writer ringbuffer safe would break down.

Forget about the compiler, the hardware instruction pipeline could
reorder ANYTHING that is unsynchronized. Plus two different threads
might read/write to different cache memories. Here's a paragraph from
the Double Chekced Locking is Broken Declaration
(http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html):

"... processors have their own locally cached copies of memory. On
some processors, unless the processor performs a cache coherence
instruction (e.g., a memory barrier), reads can be performed out of
stale locally cached copies, even if other processors used memory
barriers to force their writes into global memory."

There's in link in that article to how that can happen on an Alpha.

>> > AFAIK nothing fatal can happen if the variables involved
>> > are declared volatile. A compiler is not allowed to

The only thing that volatile accomplishes is to slow down
properly-synchronized programs. volatile is for signal handlers and
interrupt handlers, not for threading.

> read/write are not strict functions, the only thing that counts is if you have
> space for reading/writing. And that is fulfilled if read_ptr!=write_ptr...

This is not the real problem. Here's where reordering can hurt:

"Without full sync, a non-owned pointer can "appear" to
  change before the pointed data is ready (due to cache non-coherence
  and access reordering by compiler or hardware). E.g. the consumer
  may "see" the write pointer move before its view of the pointed data
  is up-to-date, leading to bogus data. Alternatively, the producer
  may "see" the read pointer move before the consummer finishes
  loading the pointed data; the producer will thus see the
  still-in-use data as empty space and may overwrite it, leading to
  lost frames."

(From the write-up at the end of my own program, sintvert.c, at
https://github.com/danmbox/sintvert/blob/master/sintvert.c)

This reordering cannot be prevented without proper synchronization. So
my advice to anyone considering this would be to drop volatile and do
proper synchronization at the application level (i.e. semaphores,
since it has to work in real time).


-- Dan



More information about the Linux-audio-dev mailing list