[linux-audio-dev] realtimeness: pthread_cond_signal vs. pipe write
stefan at space.twc.de
Tue Jul 11 22:26:14 UTC 2006
On Tue, Jul 11, 2006 at 05:06:03PM -0400, Dave Robillard wrote:
> On Mon, 2006-06-05 at 01:21 +0200, Stefan Westerfeld wrote:
> > I am trying to notify a high priority (nice -20 or nice -19) thread from
> > a realtime thread (from a jack callback to be precise). Of course I want
> > the realtime thread to not block, but I want the high priority thread to
> > react as soon as possible. For the first implementation, I used a
> > condition, and pthread_cond_signal. But as I can't aquire a mutex within
> > the realtime thread, at least not always (at most with trylock()), this
> > results in racy code.
> > Also, it doesn't integrate well with poll(), which the high priority
> > process should be able to use. So basically I want to switch to a pipe
> > write() instead of pthread_cond_signal.
> I seem to be alone on this, but I still say semaphores are the best for
> this - sem_post is async signal safe. It might not be pedantically
> "realtime safe" (depending what the Linux guys have done with futexes I
Well after Lee's reply, and looking at the code again, I think I think
the Linux guys did everything right, and semaphores should be realtime
> but it's certainly far better than a mutex/cond pair (and I would
> guess better than writing to a pipe as well). A mutex obviously isn't
> async signal safe, and I doubt writing to a pipe is either.
> It's also handy that a semaphore is a counter, so you can easily
> gracefully handle the case where the realtime thread is going a lot
> faster than the consumer, or the consumer gets hung up for a little bit,
> Semaphores seem about perfect for this to me.. am I missing something?
Since we've been comparing different methods here, I thought I might as
well write a benchmark, to look at the performance, too. I wrote a
little test which repeatedly switches between two threads, which wakeup
eachother using a pipe, cond or semaphore.
On an AMD64 3400+ (2200 MHz) running a 126.96.36.199 kernel with preemption
enabled, the timings for 1000000 iterations (each thread runs a brief
period of time 1000000 times) are
- about 5.7 seconds when using a wakeup pipe and poll
- about 5.7 seconds when using a condition with mutex
- about 2.0 seconds when using a semaphore
So: if what you're doing doesn't restrict you in any way, then
semaphores are probably the thing to use.
If you need to wait for multiple things simultaneously (like audio
device fd and another thread), then you can do it with pipes and poll,
but not with semaphores.
Stefan Westerfeld, Hamburg/Germany, http://space.twc.de/~stefan
More information about the Linux-audio-dev