Skip to content

Instantly share code, notes, and snippets.

@joaoluizn
Created February 27, 2019 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaoluizn/84906f6c20161f7a8170a86ecc5d8ea0 to your computer and use it in GitHub Desktop.
Save joaoluizn/84906f6c20161f7a8170a86ecc5d8ea0 to your computer and use it in GitHub Desktop.
philosopher
import thread
import time, random
import threading
fork = list()
for i in range(5):
fork.append(threading.Semaphore(1))
def philosopher(f):
f = int(f)
while True:
# left fork
fork[f].acquire()
# right fork - circular approach
fork[(f + 1) % 5].acquire()
print("Philosopher %i eating..." %f)
time.sleep(random.randint(1, 5))
fork[f].release()
fork[(f + 1) % 5].release()
print("Philosopher %i thinking..." %f)
time.sleep(random.randint(1, 10))
for i in range(5):
# Starting Threads with philosophers
thread.start_new_thread(filosofo, tuple([i]))
while 1: pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment