Skip to content

Instantly share code, notes, and snippets.

@joaoluizn
Created February 28, 2019 03:46
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/2c2b3ee2da0bddfc113167b61189d1e0 to your computer and use it in GitHub Desktop.
Save joaoluizn/2c2b3ee2da0bddfc113167b61189d1e0 to your computer and use it in GitHub Desktop.
philosopher_deadlock.py
import thread
import time, random
import threading
fork = list()
# Fixed eating time
eating_time = random.randint(1, 4)
for i in range(5):
fork.append({'status': False, 'owner': None})
def eat(left_fork, right_fork, f):
left_fork.update({'status': True, 'owner': f})
right_fork.update({'status': True, 'owner': f})
print("Philosopher %i eating..." % f)
time.sleep(eating_time)
left_fork.update({'status': False, 'owner': None})
right_fork.update({'status': False, 'owner': None})
time.sleep(random.randint(1, 4))
def philosopher(f):
f = int(f)
left_fork = fork[f]
right_fork = fork[(f + 1) % 5]
while True:
if left_fork.get('status') == False and right_fork.get('status') == False:
eat(left_fork, right_fork, f)
# left held e right free
elif left_fork.get('status') == True and right_fork.get('status') == False:
right_fork.update({'status': True, 'owner': f})
if left_fork.get('owner') == f:
eat(left_fork, right_fork, f)
else:
print("Philosopher %i thinking" %f)
time.sleep(random.randint(1, 4))
# left free right held
elif left_fork.get('status') == False and right_fork.get('status') == True:
left_fork.update({'status': True, 'owner': f})
if right_fork.get('owner') == f:
eat(left_fork, right_fork, f)
else:
print("Philosopher %i thinking" %f)
time.sleep(random.randint(1, 4))
# both held by another philosopher
elif left_fork.get('status') == True and right_fork.get('status') == True:
print("Philosopher %i thinking" %f)
time.sleep(random.randint(1, 4))
for i in range(5):
# Starting Threads with philosophers
thread.start_new_thread(philosopher, tuple([i]))
while 1: pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment