Double Buffering

I am trying to implement a class for Double Buffer.
Ill also need 2 threads, 1 to generate samples, and the other to play them

heres the project link
https://filebox.ece.vt.edu/~ECE3574/projects/03-threaded-synthesizer/

I need help implementing shared double buffer.cpp and hpp
IIRC a double buffer is just 2 pointers to containers and you swap the pointers every iteration. The active one is fed to the hardware while the other one is filled with new data, flip and repeat.

I don't know that you want to mix the threads and buffers into one thing; seems like a double buffer class should stand alone (?).
when and where do I swap?

my doublebuffer class has an add and remove function

add will push the sample into buffer 1

remove will return the 1st element of buffer2 and pop_front
I will admit I am not sure for music. For graphics, it was easy... you swapped buffers when you finished drawing the new frame, as fast as you could do it. For music though, you need precise timing to flow. I am *guessing* that you swap when the player thread is done with its current buffer. It then takes the new buffer, which *should* be full, but if not it burns out what it gets and then swaps again (so it will need to know if the buffer is full or partly full). If the software is unable to keep up, you will end up eventually swapping empty buffers and having audio stutter. So you have to ensure you can fill slightly faster than you play on the target or better systems.

pop front is ineffiicent. Consider trying to rewrite the code so that you can do something better. Maybe create a circular buffer type container.
Last edited on
Canonically, sample frames are streamed into a single circular buffer. This offers the client some leeway when filling the buffer - to an extent.

Multi-threaded programming is intended to address performance problems. That is, threads are something you use when you have a parallelizable problem and need extra performance.

The same is not intended as a hack to do more than one thing at once. That is, there are no guarantees that your threads actually run in parallel, nor any guarantees regarding when your threads run - and with that you're also forced to deal with synchronization, making your software significantly more complicated.
Last edited on
^^^^ This, so much this.

I have used the thread 'hack' to do 2 *completely unrelated* things at once that were 100% decoupled. That is safe enough.
Topic archived. No new replies allowed.