Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from threading import Thread, Lock, Semaphore
- import time
- import sys
- class Philosoph(Thread):
- def __init__(self, leftlock, rightlock, i):
- Thread.__init__(self)
- self.leftLock = leftlock
- self.rightLock= rightlock
- self.index = i
- def run(self):
- s.acquire()
- self.leftLock.acquire()
- self.rightLock.acquire()
- print('I am philosopher %s and I am eating-thinking' % self.index)
- self.leftLock.release()
- self.rightLock.release()
- print('I am philosopher %s and I finised and released the chopsticks' % self.index)
- s.release()
- SIZE = 6
- philosophers = []
- locks = []
- s = Semaphore(SIZE - 1)
- for i in xrange(SIZE):
- lock = Lock()
- locks.append(lock)
- for i in xrange(SIZE - 1):
- philosopher = Philosoph(locks[i % SIZE], locks[(i + 1) % SIZE], i)
- philosophers.append(philosopher)
- philosopher = Philosoph(locks[0], locks[SIZE - 1], SIZE - 1)
- philosophers.append(philosopher)
- for i in xrange(SIZE):
- philosophers[i].start()
- for i in xrange(len(philosophers)):
- philosophers[i].join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement