Semaphore or what should I use?
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Mon Dec 6 03:23:16 EST 2004
Sergei Organov a ecrit :
> Pierre Barbier de Reuille <pierre.barbier at cirad.fr> writes:
>
>
>>Ville Vainio a ecrit :
>>
>>>>>>>>"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).
>
My point is : semaphore is more complex than what he needs. Event are
simpler and just do what he needs : block one thread until another one
finished some jobs and launchs the event (have a look at my example).
Afterward, I agree that the concept of mutex is the most general : you
can implement every other kind of lock using just mutexes.
Pierre
More information about the Python-list
mailing list