MidiBuffer + Critical Section


my plugin generates Midi messages to output to a physical Midi output.
To do so, I use a public MidiBuffer to what I add all the messages to output and let a
background thread then swaps this public MidiBuffer with the background
thread its private MidiBuffer. Then the thread iterates that private buffer to sends its messages
to the physical output and clears the public MidiBuffer afterwards.

Since I also have to THRU incoming Midi events, another thread (Midi input callback) is involved
and will probably add some incoming events to the public MidiBuffer while
this buffer is being iterated or cleared or swapped. Aslo the user will probably add Midimessages
to the buffer at the same time when he drag a slider of the UI.
So I have to make the whole thing thread safe….

Can’t use MidiMessageCollector here (which has thread safe methods) because Non Realtime Messages
i.e. Sysex can go to the MidiBuffer as well.

My first idea was to create my own buffer class inherited from MidiBuffer and Critical Section
because I read in another C++ forum that this is a possible way.

What does the Juce experts say about this? Is it a common way or rather a stupid thing to do
and if so, would you please point me to the right way?

Thank you!

For god’s sake don’t go inheriting from MidiBuffer or CriticalSection!


You can of course use a midibuffer and a criticalsection together to do that job if you want to, and it’ll probably work fine. Might be smarter to use a circular buffer of MidiMessages though, using the AbstractFifo class.

Thank you for your suggestion and that nice link!
As a not native English speaking German it isn’t always easy to understand
programmer guides but this one is really clear and understandable.



I think ScopedLock or TryScopedLock will do the trick here.

Just one question:
Since I have to cope with input and output buffers here and don’t want to lock
the input buffer while adding events to the output buffer and vice versa,
I would like to use 2 x Critical Section in on class, one for input and one for output.

Would that be okay?

Thanks Joerg