[alsa-devel] Races in alsa-lib with threads

Trent Piepho tpiepho at gmail.com
Tue Nov 13 20:41:40 CET 2012

On Tue, Nov 13, 2012 at 8:50 AM, Takashi Iwai <tiwai at suse.de> wrote:
> At Tue, 13 Nov 2012 13:39:24 +0000,
> Krakora Robert-B42341 wrote:
>> The way that the GStreamer ALSA Sink Plugin is using ALSA Lib assumes that it is thread safe.  The fix crafted by one of Trent's colleagues (attached) seems to be the way to go.  However, I don't know how it would impact other functionality within ALSA Lib.
> No, sorry, we don't want to introduce pthread_lock in alsa-lib PCM
> stuff.

The problem with introduction serialization outside alsa-lib is that
you must now serialize entire ALSA calls.  The locks must be held for
far too long.

Consider snd_pcm_writei(), most of the time is usually spent blocked
waiting for a period to elapse.  It is perfectly ok to call
snd_pcm_delay() during this time.  But if one isn't allowed to make
any other pcm calls during snd_pcm_writei() then this can't be done.

It's a pretty big problem.  Most code using blocking mode is going to
write another period as soon as the writei call returns from the last
write.  It will spend almost all its time inside snd_pcm_writei() and
thus will always be holding the app's pcm stream lock.  As soon as it
releases the lock it grabs it again for the next write.  Another
thread trying to call snd_pcm_delay() will virtually NEVER get a
chance.  Not only is it unnecessary stopped from getting the delay
while another thread is blocked inside writei(), but it won't get a
chance to call it between writei() calls either.

But there doesn't need to be a conflict, since the actual critical
section that needs locking is very small, far smaller than the time
spent sleeping inside writei() or wait().  How can just the critical
section be protected without placing the locking inside alsa-lib?

More information about the Alsa-devel mailing list