Is AudioBuffer::copyFrom() thread safe?

is it safe to call at the same time in two separated threads this:

// Let's say in AudioProcessor::precessBlock()
myTempAudioBuffer.copyFrom(ch1, start1, audioBufferInProcessBlock, ch1, start2, numSamples1);

// And now at the same time in message thread
bufToUseInMessageThread.copyFrom(ch2, start3, myTempAudioBuffer, ch2, start4, numSamples2);

And also the same question is about AbstractFifo. I mean what happen if I call:

// in processBlock
myAbstractFifo.prepareToWrite (numSamples1, start1, block1, start2, block2);

// And exactly at the same time in message thread

As you can see I need to collect data in AudioProcessor::processBlock() and then use that data in message thread. And not sure how to do that properly. I thought about something like AudioBuffer<std::atomic<float>> but of course it doesn’t work with copyFrom() and things like that.

For any help great thanks in advance.
Best Regards.


No, your first code block is definitely not thread safe at all.

You’re on the right track that if you want to collect data on your audio thread and use these data on another thread, AbstractFifo is probably a good option. Never looked into the guts of AbstractFifo, but since it’s designed exactly for this kind of problem, i imagine that as long as:

  • Your data writing (on the audio thread) is enclosed within AbstractFifo::prepareToWrite and AbstractFifo::finishedWrite
  • Your data reading (on another thread) is enclosed within AbstractFifo::prepareToRead and AbstractFifo::finishedRead
  • You only have one producing thread and one consuming thread

then you’re good to go.

Great thanks for your answer.
While AudioBuffer<float>::.copyFrom() operates on simple pointers to the block of data, and AbstractFifo guards to not use blocks which are not already copied then you are probably right.

So all safety depends on AbstractFifo. That’s why I also asked if AbstractFifo is safe thread while calling prepareToWrite() and finishedRead().

But now I’ve just debug it and it looks like AbstractFifo operates on juce::Atomic<int>.
So it looks like I have the answer.

Thanks for your help.