Re: [RFC] unify semaphore implementations

Paul Mackerras
2005-04-30T05:13:14Z

I wrote:

> The only fast path that needs atomic_dec_if_positive is down_trylock.
> You can use atomic_dec for down_trylock instead; the only downside to
> that is that if somebody was holding the semaphore but nobody was
> waiting, the holder will take the slow path when it does the up.

Better still, on machines without ll/sc we can do down_trylock as:

return atomic_read(&sem->count) <= 0
|| atomic_add_negative(-1, &sem->count);

Then we will only take the slow path unnecessarily on up() if another
cpu decrements the count between the test and the atomic_add_negative,
which should be very rare. Doing the test will also avoid doing the
atomic op if the semaphore is already held.

Paul.