andrewrk / libsoundio

C library for cross-platform real-time audio input and output
http://libsound.io/
MIT License
1.92k stars 229 forks source link

Mutex for Ring Buffer #148

Open adesutherland opened 7 years ago

adesutherland commented 7 years ago

One enhancement to consider is to provide a mutex capability for the ring buffer - must be a common use case?

Apologies if I have missed this - I did quickly review the source code. And I also totally understand that you might feel this extends the scope of your library too far.

Using your library with libspotify - so thanks!

andrewrk commented 7 years ago

can you elaborate? I don't understand what a mutex capability means.

Yepoleb commented 7 years ago

I think he wants a thread safe ring buffer and looked at the source to check if it has an internal mutex. Because there is none, he assumed they are not thread safe and is requesting one. I think that's a plausible interpretation for someone who most likely isn't used to all the magic you do with atomics.

adesutherland commented 7 years ago

Andrew / Gabriel - thank you for your replies.

Gabriel's interpretation of my request is 100% correct.

I also did notice that the microphone example does not need / use any locking - but I was wondering if that was made possible by the way SoundIO fires the callbacks. After all could not one thread be writing to the buffer while another is reading? Even if the buffer functions to advance the pointers are thread safe, is this not a problem?

But is it all good? I might not be understanding the ring buffer properly. It sounds like that not only are the calls to the ring buffer atomic, but that it also keeps the read and write areas separate (which makes sense). And in short - I don't need to worry about any mutexes, if this is true - thank you!

It would be great to add a comment to the docs :-)

ul commented 7 years ago

Read and write pointers are updates atomically. If I understand correctly it's enough to make ring buffer thread-safe in single-producer/single-consumer scenario.

ssfrr commented 7 years ago

In fact you must avoid mutexes in the audio callback on some platforms. The callback is run from a high priority thread (or sometimes interrupt) and should never block, which is why lock-free ringbuffers like these are used.