Created
February 27, 2019 19:33
-
-
Save joaoluizn/84906f6c20161f7a8170a86ecc5d8ea0 to your computer and use it in GitHub Desktop.
philosopher
This file contains hidden or 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 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