28.06.2017 Views

Python para todos

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Python</strong> <strong>para</strong> <strong>todos</strong><br />

Como vemos los eventos son muy similares a las condiciones, a excepción<br />

de que se desbloquean <strong>todos</strong> los threads que esperaban el evento y<br />

que no tenemos que llamar a acquire y release.<br />

import threading, time<br />

class MiThread(threading.Thread):<br />

def __init__(self, evento):<br />

threading.Thread.__init__(self)<br />

self.evento = evento<br />

def run(self):<br />

print self.getName(), “esperando al evento”<br />

self.evento.wait()<br />

print self.getName(), “termina la espera”<br />

evento = threading.Event()<br />

t1 = MiThread(evento)<br />

t1.start()<br />

t2 = MiThread(evento)<br />

t2.start()<br />

# Esperamos un poco<br />

time.sleep(5)<br />

evento.set()<br />

Por último, un pequeño extra. Si sois usuarios de Java sin duda estaréis<br />

echando en falta una palabra clave syncronized <strong>para</strong> hacer que sólo<br />

un thread pueda acceder al método sobre el que se utiliza a la vez. Una<br />

construcción común es el uso de un decorador <strong>para</strong> implementar esta<br />

funcionalidad usando un Lock. Sería algo así:<br />

def synchronized(lock):<br />

def dec(f):<br />

def func_dec(*args, **kwargs):<br />

lock.acquire()<br />

try:<br />

return f(*args, **kwargs)<br />

finally:<br />

lock.release()<br />

return func_dec<br />

return dec<br />

class MyThread(threading.Thread):<br />

@synchronized(mi_lock)<br />

def run(self):<br />

print “metodo sincronizado”<br />

110

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!