#!/usr/bin/env python
# 
# Little test with the fifo named pipes.

__author__ = "Yoan Blanc <yoan at dosimple.ch>"
__revision__ = "20080119"

import os
import sys
import time
import pickle
from random import random

PIPE = "a.out"
MAX = 10

class Producer(object):
	def __init__(self, quantity):
		self.quantity = quantity
	
	def produce(self):
		for i in range(1, self.quantity+1):
			print ">>> %d" % i
			yield "%d\n" % i

class Consumer(object):
	def __init__(self, quantity):
		self.ok = True
		self.quantity = quantity
	
	def consume(self, value):
		if value != "":
			print "%d" % int(value)
			self.ok = self.quantity != int(value)

def consume():
	consumer = Consumer(MAX)
	pipe = open(PIPE, "r")
	while consumer.ok:
		
		try:
			consumer.consume(pickle.load(pipe))
		except EOFError:
			pass
		
		time.sleep(random())
	pipe.close()
	return 1

def produce():
	producer = Producer(MAX)
	for i in producer.produce():
		pipe = open(PIPE, "w")
		pickle.dump(i, pipe)
		pipe.close()
		time.sleep(random())
	return 1

def main(argv):
	if not os.access(PIPE, os.F_OK):
		os.mkfifo(PIPE, 0666)
	
	if len(argv) > 1:
		if sys.argv[1] == "producer":
			return produce()
		else:
			return consume()
	else:
		print >>sys.stderr, "Usage: %s [producer|consumer]\n" % argv[0]
		print >>sys.stderr, "Typical example: %s consumer & %s producer & (and not the opposite -> dead lock)" % (argv[0], argv[0])
		return 2	

if __name__ == "__main__":
	sys.exit(main(sys.argv))
