Last active
August 29, 2015 14:02
-
-
Save metula/b6ac0a27eed660e38209 to your computer and use it in GitHub Desktop.
This file contains 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 threading | |
import datetime | |
import time | |
import random | |
class SimpleThreadClass(threading.Thread): | |
def run(self): | |
for i in range(3): | |
now = datetime.datetime.now() | |
print("I am: ") | |
print(self.getName()) | |
print("The time is: ") | |
print(now) | |
PrintLock = threading.Lock() | |
class SafeSimpleThreadClass(threading.Thread): | |
def run(self): | |
for i in range(3): | |
now = datetime.datetime.now() | |
PrintLock.acquire(True) | |
print("I am: ") | |
print(self.getName()) | |
print("The time is: ") | |
print(now) | |
PrintLock.release() | |
def test_threads(t_class, n=2): | |
for i in range(n): | |
t = t_class() | |
t.start() | |
#test_threads(SimpleThreadClass, 2) | |
class Philosopher(threading.Thread): | |
running = True | |
def __init__(self, xname, forkOnLeft, forkOnRight): | |
threading.Thread.__init__(self) | |
self.name = xname | |
self.forkOnLeft = forkOnLeft | |
self.forkOnRight = forkOnRight | |
self.count = 0 | |
def safe_print(self, *args): | |
PrintLock.acquire() | |
print(self.name + ":", *args) | |
PrintLock.release() | |
def run(self): | |
self.safe_print("Hi!") | |
while(self.running): # Philosopher is thinking (but really is sleeping). | |
time.sleep(random.uniform(3,13)) | |
self.safe_print("I'm hungry.") | |
self.dine() | |
self.safe_print("Ate", self.count, "times.") | |
def dine(self): | |
fork1, fork2 = self.forkOnLeft, self.forkOnRight | |
locked = False | |
while self.running: | |
fork1.acquire(True) | |
locked = fork2.acquire(False) | |
if locked: | |
break | |
fork1.release() | |
self.safe_print("Swapping forks") | |
fork1, fork2 = fork2, fork1 | |
if locked: | |
self.dining() | |
fork2.release() | |
fork1.release() | |
def dining(self): | |
self.safe_print("Starting to eat.") | |
self.count += 1 | |
time.sleep(random.uniform(1,10)) | |
self.safe_print("Finished eating, leave to think.") | |
def DiningPhilosophers(t=100, seed=507129): | |
forks = [threading.Lock() for i in range(5)] | |
names = ('Aristotle', 'Kant', 'Buddha', 'Marx', 'Russel') | |
philosophers = [Philosopher(names[i], forks[i%5], forks[(i+1)%5]) for i in range(5)] | |
random.seed(seed) | |
Philosopher.running = True | |
for p in philosophers: | |
p.start() | |
time.sleep(t) | |
Philosopher.running = False | |
print("Now we're finishing.") | |
#DiningPhilosophers() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment