"""
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 profile
import sys
import string
import stackless
import time

OUTPUT = True 
MAX = 0
 
from slprofile  import Profile

def producer(channel):
    global MAX
    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):
    cStart = time.time()
    if OUTPUT:
       print "consumer ", n, "about to receive"
    channel.receive()    
    if OUTPUT:
       print "consumer ", n, "time: ", time.time() - cStart, "received next",name[stackless.getcurrent().next] 


def body():
   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 "time", time.time() - start 

if __name__  == "__main__":
   profiler = Profile() 
   profiler.run('body()')
