generator function within a generator function doesn't execute?

T

TheDustbustr

<code>
from __future__ import generators
from time import time
threads=[]

def sleep(n):
print "In Sleep"
t=time()
while (t+n>time()):
yield None

def cutscene():
yield None #start on second pass

print "\nEvil Death Knight: I will kill you now!"

sleep(1.5)
#t=time()
#while (t+1.5>time()): yield None

print "\nOur Hero: I shall fight you to the death. Bring it on!"

sleep(2.5)
#t=time()
#while (t+2.5>time()): yield None

print "\nEnd of cutscene."

def ticker():
yield None #wait till second time through
print "."
t=time()
while 1:
while (t+1>time()): yield None
t=time()
print "."

def scheduler():
global threads
try:
while 1:
for thread in threads: thread.next()
except StopIteration:
pass

if __name__=="__main__":
threads.append(ticker())
threads.append(cutscene())
scheduler()
</code>

ticker() prints out a period every second. cutscene() is a scripted game
sequence. sleep(n) should cause a delay of n seconds (but doesn't block
execution of the other microthreads (correct term?)). ticker() and cutscene()
should be running simultaneously (in effect, at least).

However, when run, the sleep function doesn't execute. It doesn't even print
"In Sleep". It never gets called, even though I say sleep(1.5) in cutscene().
Run it for yourself if you don't believe me.

Through my testing, any generator function will not execute if called from
another generator function. Regular functions work fine.

If I comment the sleep statements and uncomment the while loops, it runs as
expected. Why doesn't the sleep() function execute?

Thanks in advance.
Dustin
 
S

Sami Hangaslammi

<code>

However, when run, the sleep function doesn't execute. It doesn't even print
"In Sleep". It never gets called, even though I say sleep(1.5) in cutscene().
Run it for yourself if you don't believe me.

Calling sleep(2.5) isn't supposed to run anything. It just creates a
generator object. Calling it from within another generator makes no
difference. You need to manually unwind the sleep generator to your
scheduler, so instead of

sleep(2.5)

do

for x in sleep(2.5): yield x
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,265
Latest member
TodLarocca

Latest Threads

Top