Page 1 of 1
semaphores
Posted: Wed Oct 26, 2005 6:10 pm
by radad
Could someone explain to me how semaphores work?
They seem to have an initial count and a max count.
I am guessing the SignalSema increments the count by 1 (unless it is already at max) and WaitSema blocks until the count reaches max. But what happens to the count after it has unblocked?
Posted: Fri Oct 28, 2005 9:35 am
by radad
After some testing last night, here are my findings:
SignalSema - increases the count by 1
PollSema - decrease the count by 1
WaitSema - decreases the count by 1 but blocks if it is currently 0.
Interestingly, PollSema will decrease the count past 0 into negative values.
More interestingly, SignalSema increases the count beyond maxcount.
Does anybody understand the purpose of maxcount?
Posted: Mon Nov 14, 2005 10:06 pm
by Lukasz
The bottomline is that semaphores are to make threads wait for each other. A good example of this is the npmputs.c source available with naplink from
www.napalm-x.com. Because all printfs to host go through SIF ( basically the DMA channel(s) between EE and IOP), only one thread can do a printf at a time, to make this thread-safe npmput implements a semaphore.
If the sema value is 0, then Wait (it also decreaes the value as you mentioned) will put the calling thread into wait-state and it will be awoken when the value is 1 or greater. Signal increaes the value. So you Signal to allow one thread to go pass a Wait, but if a thread calls the same function before the sema has be signaled again, it will wait. Rule of thumb, Signal at init, Wait a beginning of your single-threaded function and Signal when function is done with its single-thread work, this will make it threadsafe.
As for the details of maxCount I would assume this is the max value of the semaphore aswell, why it doesn't work as expected only the coders at Sony know. I havn't seen any code on the PS2 which allows more than 1 thread to enter and maxCount also allows less-clever thread code to work, eg. you could do unnecessary Signals.