processBlock()/Thread question


#1

Hi. I admit that I'm very novice with threading, and I cannot find clear examples about how it work in Juce. So I would be really grateful if you could answer me this question, please.

Imagine we have a member variable like:

int32 ourVariable = 0;

 

A function that the user triggers with the interface manually (ie, mouse click) like:

void AudioProcessor::userTriggeredFunc() {ourVariable = 0;}

 

A normal processBlockprocessblock function like:

void AudioProcessor::processBlock(AudioSampleBuffer& buffer, MidiBuffer& midiMessages)

{

     ourVariable++;

}

 

And a thread, like a HighResolutionTimer calling this function each 10ms:

void AudioProcessor::timerFunc()

{

ourVariable += 2;

}

 

 

It's possible that the user triggers userTriggeredFunc() while one of these other functions are called. How would you lock it? Where would you lock? just in the userTriggeredFunc()? or in the other two functions?


#2

Your design is a bit weird with the high resolution timer. If you use that for playback, you should increment your counters in processBlock as it's the only reliable time reference you have (Your high resolution timer won't be "sample accurate").

 

Anyway, back to your original problem, you should probably be fine by using juce::Atomic<int>

 


#3

Thank you for your answer. The design is weird on purpose: I only want to learn to manage threads, it isn't for a real program :)

Atomic could work in this case, judging by its documentation, since I'm only using a simple variable. But imagine that there are a lot of complex operations in each function, that they share some variables, arrays and structs. How would you write it? ScopedLocks? Would you need to use AudioProcessor::getCallbackLock()?

 


#4

Locking the audio thread is never reccomended. See this talk where some ideas are given on how to handle bigger structures: