Skip to content

Instantly share code, notes, and snippets.

@smartkiwi
Created April 29, 2013 22:54
Show Gist options
  • Save smartkiwi/5485463 to your computer and use it in GitHub Desktop.
Save smartkiwi/5485463 to your computer and use it in GitHub Desktop.
PA1 python
"""
python 2.7.1 (cpython)
"""
from threading import BoundedSemaphore, Thread
class Png(Thread):
def __init__(self,string,lock1,lock2,times):
super(Png, self).__init__()
self.lock1 = lock1
self.lock2 = lock2
self.msg = string
self.times = times
pass
def run(self):
for i in xrange(self.times):
self.lock1.acquire()
print self.msg
self.lock2.release()
if __name__=='__main__':
sema1 = BoundedSemaphore(value=1)
sema2 = BoundedSemaphore(value=1)
print "Ready... Set... Go!"
num_times = 10
thread1 = Png("Ping",lock1=sema1,lock2=sema2,times=num_times)
thread2 = Png("Pong",lock1=sema2,lock2=sema1,times=num_times)
#Block semaphore 2 - so thread2(Pong) that tries to acquire it would be block till
# thread1(Ping) would release it after starting
sema2.acquire()
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment