Re: Behavior of semaphore's down/up functions (2.0.24)

Tom May (ftom@netcom.com)
21 Nov 1996 23:48:19 -0800


"Steven N. Hirsch" <shirsch@ibm.net> writes:

> Bo Liu wrote:
> >
> > Hi, any experts there willing to help:
> >
> > I am a new grad learning to write linux device drivers and want to
> > understand some kernel codes related to driver programming.
> >
> > I have a question on the behavior of semaphore's down/up functions..... :
> >
>
> > giving the result in /var/adm/syslog:
> >
> > process 0 down
> > process 0 got device
> > process 1 down
> > process 0 up
> > process 0 down
> > process 0 got device
> >
> > while what is expected on the last line is "precess 1 got device" because
> > precess 1 did the down before process 0 did it the second time.
>
> Don't confuse the ordering of your messages in the syslog with the
> actual execution sequence. AFAIK, the relationship between the two will
> not be deterministic.

Bo's observation is correct. Look at the code. `up' does a wake_up()
on all process waiting on the semaphore. That pretty much just moves
them all to the run queue. It does not necessarily reschedule.
Process 0 can keep running and get the sempahore again before process
1 runs and has a chance to recheck the semaphore. When process 1 does
run, it checks the semaphore and if it is still owned by somebody else
it goes back to sleep. There is no relation between the order that
processes do a `down' and sleep, and the order in which they
eventually are rescheduled and acquire the semaphore. Even if `up'
were to reschedule this would still be true. I'm speculating here,
but in the worst case a process may never get the sempahore at all, if
some other process is always scheduled in front of it.

Tom.