Skip to content

Instantly share code, notes, and snippets.

@tiagocoutinho
Last active June 28, 2019 19:56
Show Gist options
  • Save tiagocoutinho/d00229f444615c75ab608acb20385538 to your computer and use it in GitHub Desktop.
Save tiagocoutinho/d00229f444615c75ab608acb20385538 to your computer and use it in GitHub Desktop.
Dinning phylosophers threading python
import time
import random
import threading
def sleep():
time.sleep(random.random())
N = 5
sticks = [threading.Lock() for n in range(N)]
def philosopher(n):
sleep()
with sticks[n]:
sleep()
with sticks[(n+1)%N]:
sleep()
print(f'Philosopher {n} eating')
sleep()
tasks = [threading.Thread(target=philosopher, args=(i,)) for i in range(N)]
[task.start() for task in tasks]
[task.join() for task in tasks]
import random
import thredo
def sleep():
thredo.sleep(random.random())
N = 5
sticks = [thredo.Lock() for n in range(N)]
def philosopher(n):
sleep()
with sticks[n]:
sleep()
with sticks[(n+1)%N]:
sleep()
print(f'Philosopher {n} eating')
sleep()
def main():
tasks = [thredo.spawn(philosopher, i) for i in range(N)]
[task.wait() for task in tasks]
thredo.run(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment