Skip to content

Instantly share code, notes, and snippets.

@farfanoide
Last active August 29, 2015 14:06
Show Gist options
  • Save farfanoide/febfc09ab049c0bdd32c to your computer and use it in GitHub Desktop.
Save farfanoide/febfc09ab049c0bdd32c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import threading
PRODUCTS = 5
CONSUMERS = 7
def use_screen(message):
screen.acquire()
print message
screen.release()
class Producer(threading.Thread):
def __init__(self, name='Yo'):
threading.Thread.__init__(self)
self.name = name
def run(self):
for item in xrange(1, PRODUCTS):
context['empty_buffer'].acquire()
context['item'] = "Item " + str(item)
use_screen(context['item'] + " delivered.")
context['full_buffer'].release()
class Consumer(threading.Thread):
def __init__(self, name='Yo'):
threading.Thread.__init__(self)
self.name = name
def run(self):
for time in xrange(1, PRODUCTS):
context['full_buffer'].acquire()
if context['consumed'] < CONSUMERS - 1:
use_screen(
"I'm consumer [" + str(self.name) + "] reading " +
context['item'])
context['consumed'] += 1
context['full_buffer'].release()
context['barrier'].acquire()
else:
context['consumed'] = 1
context['empty_buffer'].release()
for each in xrange(0, CONSUMERS):
context['barrier'].release()
if __name__ == "__main__":
context = {
'barrier': threading.Semaphore(0),
'consumed': 1,
'full_buffer': threading.Semaphore(0),
'empty_buffer': threading.Semaphore()
}
screen = threading.Semaphore()
prod = Producer('prod')
consumers = [Consumer(pid) for pid in xrange(1, CONSUMERS)]
prod.start()
for consumer in consumers:
consumer.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment