"""
preferences.py

The purpose of preferences.py is to demonstrate how channel preferences
can change scheduling metrics, i.e., average response time

For this example, there is one producer and multiple consumers

usage:
preferences.py preference number_of_consumer_taskets
-1 prefer receiver
1 prefer sender
"""

import sys
import string
import stackless
import time

OUTPUT = True 
rSum = 0.0

def producer(channel):
    pStart = time.time()
    for i in range(0, MAX):
        if OUTPUT:
           print "producer about to send"
        channel.send('a')
        time.sleep(.5)
        if OUTPUT:
           print "producer sent"
    pFinish = time.time() - pStart
    print "%s: %f" % ("producer finished", pFinish) 


def consumer(channel, n):
    global rSum
    cStart = time.time()
    if OUTPUT:
       print "consumer ", n, "about to receive"
    channel.receive()    
    cFinish = time.time() - cStart
    rSum = rSum + cFinish
    if OUTPUT:
       print "consumer ", n, "received", "time: ", cFinish 


if __name__ == "__main__":
   name = {} 
   channel = stackless.channel()
   channel.preference = string.atoi(sys.argv[1]) 
   MAX = string.atoi(sys.argv[2])
 
   start = time.time()

   for i in range(0,MAX):
       t = stackless.tasklet(consumer)(channel, i)
       name[t] = i

   t = stackless.tasklet(producer)(channel)
   name[t] = "producer"

   stackless.run() 
   print "execution time", time.time() - start, "average response: ",rSum/MAX 
  
