from multiprocessing import Process, Semaphore, Lock
buffer = []
empty = Semaphore(2)
full = Semaphore(0)
lock = Lock()
class Consumer(Process):
def run(self):
global buffer, empty, full, lock
while True:
print buffer
full.acquire()
print 'Consumer buffer', buffer
lock.acquire()
print buffer
buffer.pop()
print('Consumer pop an element, Now buffer', buffer)
lock.release()
empty.release()
class Producer(Process):
def run(self):
global buffer, empty, full, lock
while True:
empty.acquire()
lock.acquire()
buffer.append(1)
print('Producer append an element, Now buffer', buffer)
print buffer
lock.release()
full.release()
if __name__ == '__main__':
p = Producer()
c = Consumer()
p.daemon = c.daemon = True
p.start()
c.start()
p.join()
c.join()
print 'Ended!'