Benno Senoner wrote:
Martijn Sipkema wrote:
It is often heard in the Linux audio community
that mutexes are not realtime
safe and a lock-free ringbuffer should be used instead. Using such a lock-free
ringbuffer requires non-standard atomic integer operations and does not
guarantee memory synchronization (and should probably not perform
significantly better than a decent mutex implementation) and is thus not
portable.
Why not portable ? on x86 you have guaranteed atomicity of 32bit
read/writes and using the read_ptr / write_ptr
approach guarantees that you will never get bad values for the
ringbuffer pointers. The worst that could happen
is that the reader reads an "old" value and thus getting a bit smaller
available read space from the ringbuffer but
given the asynchronous nature of multithreaded apps this is completely
meaningless.
Indeed, for such a ringbuffer atomicity (as in test-and-set) is not needed,
but there needs to be memory synchronization. According to POSIX, you
can not read/write to a memory location from different threads without
using a function to synchronize memory:
"Applications shall ensure that access to any memory location by more than
one thread of control (threads or processes) is restricted such that no thread
of control can read or modify a memory location while another thread of
control may be modifying it. Such access is restricted using functions that
synchronize thread execution and also synchronize memory with respect to
other threads."
Thus, the lock-free ringbuffer is not portable. (What if the reader gets an
"old" value that is never updated?)
(the audio thread does not know/care when then disk
thread writes data
into the ringbuffer)
PPC guarantees 32bit atomicity too so the atomic macros we are using in
LinuxSampler simply translate to a load or a store on
both x86 and PPC and if future CPUs with non atomic access arise , just
add the macro in atomic.h.
I would not call that "non portable".
I think there are architectures where supporting this might not be trivial, but
I'm no expert. That's why I'd always use mutexes for this...
posix mutexes are not portable because they don't
work on win32 so in
general applications with a certain complexity always require some
platform dependent code (either OS or CPU dependent) to
be portable on that platform.
With portable I mean that it will work on any POSIX compliant operating
system.
[...]
About performance, nothing can beat lock free
ringbuffers because it's
simply a few machine instructions that access
a read_ptr, write_ptr and return the address of the object you want to
read/write.
I did not say a mutex would beat lock free ringbuffers, I said that using a
mutex instead shouldn't cause a significant performance penalty for typical
use in a realtime audio application.
--ms