Well let's start with this simple example about the Producer-Consumer problem as you may saw it in the last semester, if you didn't, don't worry about it I'm gonna explain it.
The producer-consumer problem illustrates the need for synchronization in systems where many processes share a resource, in this problem, two processes share a fixed-size buffer.One process produces information and puts it in the buffer, while the other process consumes information from the buffer.These processes do not take turns accessing the buffer, they both work concurrently.Instead processes, we're gonna use threads to solve that problem.
Now that we have defined the problem, we're gonna program using threads and a module called Condition, with Condition we can handle the behavoir from each thread, we need to handle one thread called Producer and another called Consumer without any kind of conflict.
from threading import Thread, Condition
import time, random
class Productor(Thread):
def __init__(self, lista, condicion):
Thread.__init__(self)
self.lista = lista
self.condicion = condicion
def run(self):
while True:
lista = random.randint(0,10)
self.condicion.acquire()
print 'Condicion adquirida por %s' % self.name
self.lista.append(lista)
print '%d agregado a la lista por %s' %(lista, self.name)
print 'Condicion notificada por %s'%self.name
self.condicion.notify()
print 'Condicion liberada por %s'% self.name
self.condicion.release()
time.sleep(1)
class Consumidor(Thread):
def __init__(self,lista,condicion):
Thread.__init__(self)
self.lista=lista
self.condicion = condicion
def run(self):
while True:
self.condicion.acquire()
print'condicion adquirida por %s'%self.name
while True:
if self.lista:
lista = self.lista.pop()
print '%d removido de la lista por %s' % (lista, self.name)
break
print'Condicion espera por %s' % self.name
self.condicion.wait()
print'condicion liberada por %s' % self.name
self.condicion.release()
def main():
lista = []
condicion = Condition()
hilo1 = Productor(lista, condicion)
hilo2 = Consumidor(lista, condicion)
hilo1.start()
hilo2.start()
hilo1.join()
hilo2.join()
main()
You'll see something like the picture below.
Sources:
http://chuwiki.chuidiang.org/index.php?title=Hilos_en_python#Condition
http://code.google.com/p/chuidiang-ejemplos/source/browse/trunk/python-hilos/src/threading_hilo_condition.py