Thread Safe Buffer Filling/Draining

Started by
1 comment, last by The_Neverending_Loop 11 years, 8 months ago
Okay, I somehow feel this shouldn't be that hard but I cant seem to wrap my mind around doing it in a way that wont potentially end to corrupted data.

This is the basic scenario, I have 2 threads, one of these threads handles audio "streaming". Basically the audio to be played is put into a ByteBuffer array from the main thread, the audio thread is responsible with pushing said data to the line device.

Now the thing is I can see alot of things going wrong and I can't seem to find a good example on the internet, hopefully someone here might be able to point me in the right direction. So these are my basic needs.

Say we have a ByteBuffer with capacity K, the ByteBuffer is continually filled with audio data and is draining equally as fast in order to now have a Buffer Overflow Exception. Now because of the nature of byte buffer its a little tricky because of its positioning, I need it to act basically like a Queue in First in First out order, I want the new data to be automatically be appended to the end of the tail while reading from the head. I'm able to do said things in a kind of patch work type manner right now, but I feel it is open to data corruption (i.e it accidently writes the newested data a bit before the tail because the markers I keep were updated properly.


Should i try to tackle this in another way without using ByteBuffer? or is there a psuecode type manner to implement this with the ByteBuffer. Thank you for your time.
Advertisement
It doesn't sound like it should be all that difficult, you just need to use a mutex and lock it before pushing data onto the back of the queue, and lock it before removing data from the front of the queue. You also need to lock it in the audio thread when determining how much data is in the queue, though you probably don't need to keep it locked on the audio thread while actually pushing the data to the device.

On the other hand, it might make more sense and be easier to manage to just use a queue of audio chunks instead of a single byte array. Then you can just use a basic thread-safe queue for pushing/popping chunks on and off the queue. If you use a pool of pre-allocated chunks it will probably be more efficient too.
Thanks Krippy thanks actually what I ended up doing last night, I just decided to use vectors with audio chunks (since vectors are already thread safe), and everything seems to be working well so far.

This topic is closed to new replies.

Advertisement