[Portaudio] Allow tweaking PA callback thread scheduler and priority

Alan Horstmann gineera at aspect135.co.uk
Sun Mar 20 14:02:01 EDT 2016

Hi Markus,

Thanks for posting your changes.  It is probably me that needs to pick this 
up, though I am not expert in thread scheduling and priorities.  So I've done 
a little background reading...

On Saturday 19 March 2016 17:15, Markus Svilans wrote:
> Recently I was working on an embedded Linux project, with several
> threads at various SCHED_RR and SCHED_FIFO priorities. I found that the
> PortAudio stream was getting interrupted with overflows and underflows
> now and then, because PA callback thread was getting pre-empted by other
> threads. The default PortAudio real-time scheduling was being set to
> SCHED_FIFO at a priority of 1.
> To work around the issue, I changed the PortAudio callback thread to use
> the SCHED_RR scheduler and the highest priority. Now the audio stream
> does not get interrupted. The attached patch shows what I did. It is
> based on code from PortAudio SVN rev 1919

From my limited reading, I would have thought SCHED_FIFO would have been 
correct, but indeed the priority of 1 does look rather low, and the comment:

"/* Priority should only matter between contending FIFO threads? */"

looks bogus?  IIUC priority is the primary selector, and policy only 
influences the choice between threads of equal priority?  SCHED_RR would mean 
that thread gets a limited time-chunk whereas _FIFO means it will be always 
allowed to complete (once it gets a turn)?

> With the patch, you can control the callback thread scheduler and
> priority using two #defines:
> I set the defaults to SCHED_RR and sched_get_priority_max(SCHED_RR),
> respectively.

Did you try simply:

spm.sched_priority = sched_get_priority_max(SCHED_FIFO);

as I would have expected that to be equally, or more, effective?

Maybe 'PaAlsa_EnableRealtimeScheduling()' should interpret the value given as 
a rough 0-9 priority setting rather than just an 'int-bool'?  With '9' 
setting _priority_max() and the other values scaled approximately, but it's 
just a quick idea.



> As a side not, if you want real-time scheduling for your PA callbacks,
> don't forget to activate real-time scheduling on your audio stream:
> #include <pa_linux_alsa.h>
> ...
> PaStream *stream;
> ...
> // initialize audio stream etc. etc.
> ...
> PaAlsa_EnableRealtimeScheduling(stream, 1);
> ...
> // start audio stream
> This patch hard-codes the scheduler options, but in the future people
> might find it useful to add these properties to the PaStream struct, so
> they can be tweaked at runtime and/or on an OS specific basis.
> Thank you and best wishes,
> Markus

More information about the Portaudio mailing list