This is the mail archive of the ecos-discuss@sourceware.cygnus.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: Semaphores and context switch


Daniel Kahlin <tlr@netinsight.se> writes:

> I have 2 processes running at equal priority (MLQUEUE), and two semaphores
> (sem1 & sem2) which are initially zero.
> 
> (1) Process 1 polls a semaphore (and some hardware) using
>     cyg_semaphore_trywait(sem1).   Process 2 sets up a bunch of things,
>     and then does cyg_semaphore_post(sem1), and cyg_semaphore_wait(sem2)
> 
> (2) Process 1 will eventually see the post, do some processing, and then
>     do cyg_semaphore_post(sem2).
> 
> (3) Process 2 continues, and can use the data from process 1 if necessary.
> 
> Now, am I right in assuming that the context switch after
> cyg_semaphore_wait(sem2) in (1) will occur at next tick instead
> of exactly when cyg_semaphore_wait(sem2) is called?

The switch should occur immediately, since now only process 1 is
runnable. However, if process 2 was timesliced before it called
cyg_semaphore_wait(sem2), you are going to have to wait an entire
timeslice period before being timesliced back to process 2.

> 
> The same goes for the cyg_semaphore_post(sem2) in (2), will the context
> switch occur at the next tick or when the call is made?

In this case it may not happen until the next timeslice since process 1 is
still running and process 2 will go behind it on the queue.

> 
> Will this also apply to a cyg_thread_yield() ?

cyg_thread_yield() moves the current thread to the back of it's
priority queue, giving any other threads at the same priority a chance
to run. If process 1 calls cyg_thread_yield() each time around its
loop, then this will give process 2 a chance to run whenever it can.

> Q:
> If this is so, how can I make the switch occur faster?
> My current workaround would be increasing the tick rate.
> 

Putting the cyg_thread_yield() into process 1's loop is the best
approach for the described situation. But, you are always going to get
some scheduling anomalies when you have two threads fighting it out at
the same priority like this.

Personally, I wouldn't do it this way in the first place. I would
maybe make process 2 higher priority than process 1 so that when it
has work to do, it gets in, does its thing and gets out quickly. This
is assuming that process 2 actually spends most of it's time waiting
in cyg_semaphore_wait(sem2). Another approach is to make process 1
wait on an alarm between doing work. In this case process 1 should be
higher priority. Of course I don't know exactly what your program is
doing, so neither of these approaches may be applicable.

-- 
Nick Garnett
Red Hat, Cambridge, UK

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