"""
The purpose of serverTest.py is to examine how channel preferences change
scheduling order

For this example, there is one producer and multiple consumers

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

import sys
import string
import stackless
import time

OUTPUT = True 
count = 0
rSum = 0.0

def countSwitches(prev,next):
    global count 
    count += 1


def producer(channel):
    pStart = time.time()
    for i in range(0, MAX):
        if OUTPUT:
           print "producer about to send"
        channel.send('a')
        if OUTPUT:
           print "producer sent", "next", name[stackless.getcurrent().next]
    pFinish = time.time() - pStart
    print "%s: %f %s: %f" % ("producer finished", pFinish, "throughput", MAX/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, "time: ", cFinish, "received next",name[stackless.getcurrent().next] 


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

   stackless.set_schedule_callback(countSwitches)

   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 "time", time.time() - start, "switches: ", count, "average response: ",rSum/MAX 
  
