Semaphore or what should I use?

Sergei Organov osv at javad.ru
Thu Dec 2 14:41:56 CET 2004


Pierre Barbier de Reuille <pierre.barbier at cirad.fr> writes:

> Ville Vainio a Иcrit :
> >>>>>>"Bastian" == Bastian Hammer <webmaster at haustierworld.de> writes:
> >     Bastian> Now I have to make sure, that both threads are
> 
> >     Bastian> synchronal, 1 thread edits something and the other is
> >     Bastian> blocked until the first thread is ready.
> >     Bastian> Isn╢t it a good idea to do this with a semaphore?
> 
> > Semaphore will do, but this is a classical use case for
> > threading.Lock.
> >
> > There should be lots of stuff regarding locks (or more googleably,
> > "mutexes") on the net.
> >
> 
> 
> I don't agree. Mutexes (or locks) are best suited for critical sections (ie.
> sections that cannot be run by many thread at the same time).

Please don't add even more confusion to the issue. Mutex conceptually is
designed to be used for MUTual EXclusion of access to a resource (e.g.,
a peace of data). While critical section could be implemented using
mutex, the mutex itself is more general concept. Besides, the rule of
thumb using mutexes is: "protect data, not program code."

My answer to OP's question is: use either lock (mutex) or semaphore.
I'd probably use semaphore as mutexes are usually optimized for the case
when contention probability is low (i.e., they usually shouldn't be locked
for a long time).

-- 
Sergei.



More information about the Python-list mailing list