Last active
June 28, 2019 19:56
-
-
Save tiagocoutinho/d00229f444615c75ab608acb20385538 to your computer and use it in GitHub Desktop.
Dinning phylosophers threading python
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 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] |
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 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