Jump to content
  • Advertisement
Sign in to follow this  
The_Neverending_Loop

Thread Safe Buffer Filling/Draining

This topic is 2130 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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. Edited by krippy2k8

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!