import stackless
from stacklessmulticore import new, Sleep, run

def looping_tasklet(me):
    n = 5
    while n > 0:
        n -= 1
        print me, "looping", n
        Sleep(1)
    print me, "exiting"

def looping_tasklet_r(ch):
    print "Spawned receiver.... will sleep for 3 seconds to do a receive()"
    Sleep(3)
    print "Woke up... receiving from channel...."
    msg = ch.receive()
    print "Received from other tasklet:", msg
    print "Receiver ended..."

def looping_tasklet_s(ch):
    print "Sending to other tasklet, I will block."
    ch.send("Bla!!!!!")
    print "Sender unblocked..."

def monitor(c):
    while 1:
        if c.balance != 0:
            print "----> Monitor: ", c.balance, c.queue
        stackless.schedule()

if __name__ == "__main__":
    c = stackless.channel()
    new(looping_tasklet, 1)
    new(monitor, c)
    new(looping_tasklet, 2)
    new(looping_tasklet_r, c)
    new(looping_tasklet_s, c)

    new(looping_tasklet, 3)
    new(looping_tasklet, 4)
    new(looping_tasklet, 5)
    run()
