This is the mail archive of the ecos-discuss@sources.redhat.com mailing list for the eCos project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

RE: Condition Variables recap



On 24-Jul-2001 Trenton D. Adams wrote:
>   > 
>   > "Trenton D. Adams" wrote:
>   > >
>   > > Consumer Thread
>   > > Each consumer thread starts in a loop and checks the condition
>   > variable
>   > > by calling cyg_cond_wait ().
>   > > They will either be suspended, or one will succeed.
>   > > After the producer thread calls cyg_cond_broadcast (), ONE
> consumer
>   > > thread will lock the mutex, and begin reading data.
>   > > Now this thread should call cyg_mutex_unlock () which will cause
>   > another
>   > > ONE thread to lock it.
>   > >
>   > > Now I have a question.  What happens to the cyg_cond_wait () call
> in
>   > the
>   > > OTHER consumer threads when cyg_cond_broadcast () is called?  Do
> they
>   > > simply get suspended, after that other ONE consumer thread locks
> the
>   > > mutex, and until the mutex is available to ONE of them again?
>   > 
>   > Yes. They will all have been woken up by the broadcast, and then
> each go
>   > through locking and unlocking the mutex. By that point the condition
> may
>   > no
>   > longer be true of course, i.e. there may be no more waiting data. I
>   > would
>   > imagine cyg_cond_signal() would be more appropriate (although
> there's
>   > still
>   > a chance more than one thread is woken up).
>   > 
> 
> Why would cyg_cond_signal () be more appropriate?  After all, I want my
> producer thread to continue on right away doing what it was doing.  If I
> used cyg_cond_signal () wouldn't I have to call it multiple times?  Or
> would I just have each of the consumer threads call it again when
> they're finished?
> 

The difference between cyg_cond_signal() and cyg_cond_broadcast() is that
with the former at most one thread waiting on the condition variable will
be awakened.  With cyg_cond_broadcast(), all threads waiting on the variable
will wake up.  

In most cases, it is far more efficient to wake up a single thread than it is
for a number to be awakened, only to fight over which one gets to actually
perform the service being signalled.

> Is there any way that two of the threads could accidentally lock a mutex
> at the exact same time and not even know it?  I would think that it
> doesn't really matter as long as the resource required is meant to be
> read-only to the consumer threads right?

No - if this were possible, then it would not be a mutex!  (mutex = device
for _mutual exclusion_)


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]