1
I’m developing a python code for the philosophers' dinner... for those who don’t know, follow the link: https://blog.pantuza.com/artigos/o-jantar-dos-filosofos-problema-de-sincronizacao-em-sistemas-operacionais... In this case, I’m using threads and semaphore to solve the problem... My question is when printing, because sometimes, is printing a philosopher on top of the other, as shown in the image below... I was wondering if you had a solution for that. Follow the code, and the one just below the code, the terminal image.
import thread
import time, random
import threading
garfo = list()
for i in range(5):
garfo.append(threading.Semaphore(1))
def filosofo(f):
f = int(f)
while True:
# garfo da esquerda
garfo[f].acquire()
# garfo da direita
garfo[(f + 1) % 5].acquire()
i = random.randint(1, 5)
print ("Filosofo %i comendo por %i segundos..." %(f,i))
time.sleep(i)
garfo[f].release()
garfo[(f + 1) % 5].release()
t = random.randint(1, 10)
print ("Filosofo %i pensando por %i segundos..."%(f,t))
time.sleep(t)
for i in range(5):
print ("Filosofo",i,"iniciado")
thread.start_new_thread(filosofo, tuple([i]))
while 1: pass
You put that
while 1: pass
pro program does not terminate before completing the algorithm?– Gabriel
It is important within the
while 1:
of the end put atime.sleep()
m, else athread main will consume 100% CPU making nothingness. (Battery, power, CPU temperature thank)– jsbueno