pa_threaded_mainloop_stop() blocks on pa_mutex_lock(m->mutex)
Submitted by Yupeng Chang
Assigned to pul..@..op.org
I recently switched my pulseaudio code to pulseaudio-3.0 and used pa_threaded_mainloop to use pulseaudio library in multi-threaded application. I find in some cases, pa_threaded_mainloop_stop() will just block on pa_mutex_lock(m->mutex) and never quit.
I have read the source code of pa_threaded_mainloop_stop() pa_threaded_mainloop_run(), it seems that there is one possibility that makes this happen. In pa_threaded_mainloop_run(), a thread is created and pa_mainloop_run is called and protected by pa_mutex_lock(m->mutex) and pa_mutex_unlock(m->mutex) in the thread;
in pa_threaded_mainloop_stop(), pa_mainloop_quit is also protected by pa_mutex_lock(m->mutex) and pa_mutex_unlock(m->mutex);
So, here is the problem, in pa_threaded_mainloop_stop(), m->mutex must be aquired before pa_mainloop_quit() can be called, and in pa_threaded_mainloop_run(), when pa_mainloop_run() exits, m->mutex can be unlocked. If pa_mainloop_run() is blocked, the only way to make pa_mainloop_run() exit is to call pa_mainloop_quit(), but pa_mainloop_quit() can only be called after pa_mainloop_run() is quit.
This is the deadlock.
I noticed that the mutex is created with flag RECURSIVE, which only makes this mutex can be locked recursively in the same thread. In my case, pa_threaded_mainloop_stop() is called from another thread, so the mutex still can block pa_threaded_mainloop_stop().
This is easy to reproduce, use pa_threaded_mainloop() to write a recording program, and start/stop repeatedly, sometimes pa_threaded_mainloop_stop() is deadlocked.