How smart are Semaphore Objects?

Chris Tavares christophertavares at earthlink.net
Tue Oct 30 14:48:22 EST 2001


"Matthew D. Wood" <woodm at equire.com> wrote in message
news:32cedc66.0110292253.5eaaca31 at posting.google.com...
> I firmly believe that when coding a function, object, program or
> whatever, one should assume that every other function, ... is either
> stupid or out to get you.  With this mind-set, I'm curious as to how
> (idiot or mean-person) proof semaphore objects are.
>
> Threading.Semaphore.
>
> If a class can't acquire a semaphore, or doesn't bother, can it
> release it, despite not owning it?
>
> It's almost a security thing.  I want in, and so, I will release the
> semaphore, repeatedly if necessary, until I get in.
>

[... snip ...]

There's two factors that complicate the way you're looking at this.

1) Semaphores only work if everyone plays by the rules. If you've got a
thread that's going to go straight to some resource and just not bother
calling the semaphore wait function, there's nothing you can do to stop it
regardless.

2) Semaphores are used for more than just mutual exclusion. For another
common use, think of  a thread-safe message queue. It's fairly common to
initialize the semaphore with a count of the number of messages currently
available in the queue. The reader threads will decrement the count, and
separate writer threads will increment it. If a separate thread isn't
allowed to release a semaphore, this very common usage wouldn't work.

So, I'm afraid you win some and you lose some. If you're on the windows
platform, you might want to consider using the win32 native syncronization
objects (particularly critical sections and mutexes) rather than python
semaphores - they have the kind of behavior you're looking for, since they
don't need to be so general.

-Chris






More information about the Python-list mailing list