import stackless, threading, time

waitChannel = stackless.channel()

def f():
    while True:
        print "about to wait (f)"
        waitChannel.receive()

class TokenThread(threading.Thread):
    def __init__(self, **kwargs):
        threading.Thread.__init__ (self, **kwargs)
        self.setDaemon(1)

        self.start()

    def run(self):
        while True:
            print "sleeping in other thread"
            time.sleep(2.0)


def Run():
    thread = TokenThread()

    stackless.tasklet(f)()

    while waitChannel.balance or stackless.runcount > 1:
        while waitChannel.balance < 0:
            waitChannel.send(None)

        print "about to run the scheduler (main)"
        t = stackless.run(500000)
        print "ran the scheduler", t, "(main)"
        if t is not None:
            raise RuntimeError("Runaway tasklet", t)

if __name__ == "__main__":
    Run()