(concurrency) use case :: Producer Consumer

pattern by downey

mutex = Semaphore(1)
items = Semaphore(0)
buffer = ....

Producer
mutex.wait()
    buffer.add( ... )
    items.signal()
mutex.signal()
Consumer 
items.wait()
mutex.wait()
    v = buffer.get()
mutex.signal()

java solution

scala solution

….

My python solution (threading module)

gist

"""
Producer produces numbers 1..10
Consumer runs first & then blocks
Solution: uses semaphores
"""
from threading import Thread
from threading import Semaphore
class SharedBuffer(object):    
  def __init__(self):        
    self.empty = Semaphore(0)        
    self.mutex = Semaphore(1)        
    self.slot = []

 def put(self, p):        
  """ blocking put """        
  self.mutex.acquire()        
  try:            
    print "put " + str(p)            
    self.slot.append( p )        
  except:            
    print "failed to append"        
  self.mutex.release()        
  self.empty.release()

 def get(self):        
  """ blocking get """        
  self.empty.acquire()        
  self.mutex.acquire()        
  v = self.slot.pop()        
  self.mutex.release()        
  print "get " + str(v)        
  return v
class Producer(Thread):    
  def __init__(self,buffer):        
    Thread.__init__(self)        
    self.buffer = buffer

 def run(self):        
  print "[Producer] running"        
  for i in range(0, 10):            
    self.buffer.put( i )            
    print "[Producer] sent " + str(i)
  print "[Producer] dead"

class Consumer(Thread):    
  def __init__(self,buffer):        
    Thread.__init__(self)        
    self.buffer = buffer

 def run(self):        
  print "[Consumer] running"        
  while(True):            
    v = self.buffer.get()            
    print "[Consumer] received " + str(v)            
    if( v == 9 ):                
      break                    
    print "[Consumer] dead"

if __name__ == "__main__":    
  buffer = SharedBuffer()    
  p = Producer(buffer)    
  c = Consumer(buffer)    
  c.start()    
  p.start()
 c.join()

python solution (using multiprocessing module)

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s