Create tasklets at runtime

157 Views Asked by At

Just starting with Stackless Python. I'm trying to create some tasklets at run time, that is, after calling stackless.run(). I thought this function wouldn't block the main thread, so I would be able to create new tasklets when necessary. So I decided to make a tasklet-creator function that run in a tasklet. This is what I have:

import stackless

from time import sleep

def say_hello(s):
    while True:
        print("Hello, %s!" % s)
        sleep(5)

def creator():
    i = 0
    while True:
        i += 1
        t = stackless.tasklet(say_hello)(str(i))
        t.insert()
        sleep(5)

stackless.tasklet(creator)()
stackless.run()

This code should create a new tasklet every 5 seconds, and each one should print "Hello, {number of tasklet}!" infinitely (every 5 seconds, too). The expected output is:

Hello, 1!
Hello, 1!
Hello, 2!
Hello, 1!
Hello, 2!
Hello, 3!
Hello, 1!
Hello, 2!
Hello, 3!
Hello, 4!
...

But when running the code there's no output.

What's wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

Just a guess but I think you need to call stackless.schedule() after the t.insert() before sleeping in creator(). I think creator is not giving control back. Same for say_hello.