Semaphore or what should I use?
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Thu Dec 2 06:19:36 EST 2004
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). The
kind of synchonisation Bastian want is not really semaphore either but
more event. This python "Event" object is described in the section 7.5.5
of the documentation of Python 2.3. There is no example, but I think
Event are quite strait forward : you creates it, then some thread block,
waiting the event to occure while some other thread execute until it set
the event, allowing the blocked thread to go on its own execution :)
Here a small working example :
***8<************8<***************8<**********
import threading, time
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._event = threading.Event()
self._exit = False
def run(self):
while 1:
print "Waiting for an event to continue"
self._event.wait()
print "Ok, the thread is unblocked now :)"
if self._exit:
return
self._event.clear()
def unblock(self):
self._event.set()
def exit(self):
self._exit = True
self.unblock()
t = MyThread()
t.start()
time.sleep(1)
t.unblock()
time.sleep(1)
t.unblock()
time.sleep(1)
t.exit()
***8<************8<***************8<**********
Pierre
More information about the Python-list
mailing list