Page 1 of 1

semaphores

Posted: Sat Jul 31, 2004 6:01 am
by Adek336
Hi, I wasn't sure if this was osdev specific at all so it goes to general programming.

Is this a proper implementation of semaphores:

Code: Select all

struc SEMAPHORE
   thread_list LIST
  int VAL = 1
end

to GET_A_SEM
  DEC_ATOMIC ( SEMAPHORE.VAL )
  if SEMAPHORE.VAL is above-or-equal TO zero RETURN;

  ADD-TO-THREAD-LIST ( this-thread)
  SLEEP(0)
  RETURN
end

to RELEASE_A_SEM
  if SEMAPHORE.VAL less THAN zero { AWAKE-FIRST-THREAD ( from LIST)

  INC_ATOMIC ( SEMAPHORE.VAL )
  RETURN
end
Ugh that's much to write :/ However the pseudocode seems to work;
val= 1 (semaphore-creation:)
thread-1: (val == 1) acquire sem; (val==0)
thread-2: (val==0) acquire sem; (val==-1) sleep
thread-1: (val==-1) release sem; awake thread2; val++; (val==0)
thread-2: (val==0) release sem; (val==1)

Cheers,
Adrian ;)

Re:semaphores

Posted: Sat Jul 31, 2004 9:33 am
by bi lazy
basically thats it.

You may want to put the thread on a dedicated queue for the semaphor it wants to acquire. You also may want to keep track of how much time a thread spends waiting on a semaphor. But that's all for later implementation.

Re:semaphores

Posted: Sat Jul 31, 2004 9:34 am
by bi lazy
sorry, should read a post more carefully. I 've just discovered that you already intend to put the thread into a dedicated wait queue for the semaphor.

Re:semaphores

Posted: Sat Jul 31, 2004 9:43 am
by Adek336
great. my spinlock subsytem got overgrown to a dictatorship, one thread would have the lock for a looong time because the other threads wouldn't be scheduled at the time the lock was released by the former thread. I still have some weird crashes on my output subsytem, probably race:P 'coz it happens only when two threads print at the same time.
You also may want to keep track of how much time a thread spends waiting on a semaphor
Purrrely for debugging reasons, AFAICS? Excellent8)

THX for help:)
Cheers