By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,946 Members | 1,600 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,946 IT Pros & Developers. It's quick & easy.

generator function within a generator function doesn't execute?

P: n/a
<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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
th**********@aol.com (TheDustbustr) wrote in message news:<20***************************@mb-m17.aol.com>...
<code> <snip> </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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.