This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import random | |
import time | |
class Filosofo(threading.Thread): | |
corriendo = True | |
def __init__(self, nom, tenIzq, tenDer): | |
threading.Thread.__init__(self) | |
self.nombre = nom | |
self.tenIzq = tenIzq | |
self.tenDer = tenDer | |
def run(self): | |
while(self.corriendo): | |
time.sleep(random.uniform(3, 13)) | |
print '%s esta hambriento' %self.nombre | |
self.cena() | |
def cena(self): | |
ten1, ten2 = self.tenIzq, self.tenDer | |
while self.corriendo: | |
ten1.acquire(True) | |
candado = ten2.acquire(False) | |
if candado: break | |
ten1.release() | |
print'%s intercambio de tenedores' %self.nombre | |
ten1, ten2 = ten2, ten1 | |
else: | |
return | |
self.cenando() | |
ten1.release() | |
ten2.release() | |
def cenando(self): | |
print '%s empieza a cenar' %self.name | |
time.sleep(random.uniform(1, 10)) | |
print '%s termina de comer y piensa' %self.name | |
def cenaFilo(): | |
tenedores = [threading.Lock() for n in range(5)] | |
nomFilo = ('max', 'roberto', 'juan', 'ramon', 'emman') | |
filosofos = [Filosofo(nomFilo[i], tenedores[i%5], tenedores[(i+1)%5]) \ | |
for i in range(5)] | |
random.seed(507129) | |
Filosofo.corriendo = True | |
for p in filosofos: p.start() | |
time.sleep(100) | |
Filosofo.corriendo = False | |
print "Termino" | |
cenaFilo() | |
Y muestra de su ejecución:
Bien :) 8
ResponderEliminarNecesito hablar contigo urgente, necesito la misma solución, pero que uno pueda ingresar el tiempo de llegada y la prioridad. Me podrías ayudar ?
ResponderEliminar