[ECOS] Why to signal condvar with mutex held?
Wed Nov 24 14:54:00 GMT 2004
Sergei Organov <firstname.lastname@example.org> writes:
> Browsing eCos sources and documentation, I've observed that condvars are
> usually being signalled with associated mutex locked. However, as far as
> I understand, it is sub-optimal from the point of view of execution time
> as it could lead to additional context switches. Consider the following
> 1. thread1 signals condvar.
> 2. thread2 wakes up and preempts thread1 (context switch 1) only to see
> that the mutex is locked.
> 3. thread2 goes to wait on the locked mutex, thread1 is resumed (context
> switch 2).
> 4. thread1 unlocks mutex.
> 5. thread2 wakes up and preempts thread1 (context switch 3).
> Thus, we end up with 3 context switches instead of 1.
> So there are the questions:
> 1. Does this problem actually exist, or am I missing something ?
This can happen in some circumstances.
I guess that "wait morphing" is where the thread is taken off the
condvar thread queue and inserted on the mutex thread queue and its
state changed, without being woken up. I considered this during the
design phase and decided against it. This would be the only instance
where such a thing was needed, and putting intimate details of the
threads state into the condvar code would have made some configuration
options more difficult to handle.
There are also realtime issues to consider. By letting the signalled
thread run and then fight it out in the scheduler for access to the
mutex, we ensure that the highest priority thread always gets the
mutex. With the wait morphing approach, this depends more on the
priorities of the threads signalling the condition variables.
> 2. Is it allowed in eCos to signal/broadcast condvar with mutex
> unlocked? I almost sure it is, for signalling from DSR would be
> impossible if it weren't.
> 3. If both of the above are true, isn't it better to signal/broadcast
> with mutex unlocked?
Condition variables are seldom used on their own. There is usually
some other data that encodes the condition being waited for. This data
needs to be protected with a mutex.
eCos does allow a condition variable to be signalled without taking
the mutex, but this has somewhat limited use. It is mainly used in
device driver DSR routines to wake a waiting thread up. There the role
of the mutex is played by taking the scheduler lock, or disabling
Nick Garnett eCos Kernel Architect
http://www.ecoscentric.com/ The eCos and RedBoot experts
Before posting, please read the FAQ: http://ecos.sourceware.org/fom/ecos
and search the list archive: http://ecos.sourceware.org/ml/ecos-discuss
More information about the Ecos-discuss