我在类
的某个方法中有永远的while循环@gen.coroutine
def process_task_queue(self):
while True:
#print ("Hello from async while")
if not self.q:
continue
#just example
据我所知,“while”是非阻塞的相对龙卷风io_loop。
比我用tornado.testing创建unittest
class TestMSGB(AsyncTestCase):
#@gen_test
def test_init(self):
start = time.time()
def done():
self.io_loop.stop()
print "Done"
duration = time.time() - start
#print "While worked for {} seconds".format(duration)
print "+++++++++ Test init +++++++++ "
s1 = Stream(iol=self.io_loop)
self.io_loop.current().spawn_callback(s1.process_task_queue)
self.io_loop.call_later(time.time() + 1, done) # try this way
self.io_loop.handle_callback_exception(done) # also try this way
self.io_loop.start()
正如我所料,它必须在1秒后停止,但它会继续存在。那么我该如何进行异步while循环,当龙卷风io_loop停止并且可以与其他类的实例并行工作时停止?
UPD: 修改过的代码但测试也被阻止了:
@gen.coroutine
def process_task_queue(self):
print ("Hello from async while")
while True:
item = yield self.q.get()
print ("while iter... item is {}".format(item))
try:
print('Doing work on %s' % item)
yield gen.sleep(0.1)
finally:
q.task_done()
和testcase:
@gen_test
def test_init(self):
start = time.time()
print "+++++++++ Test init +++++++++ "
s1 = Stream(iol=self.io_loop)
def producer():
for item in range(5):
yield s1.q.put(item)
print('Put %s' % item)
# as in example
self.io_loop.current().spawn_callback(s1.process_task_queue)
yield producer()
yield s1.q.join()
答案 0 :(得分:2)
您的process_task_queue
函数阻止IOLoop
,因为它不包含任何yield
语句。它只会在while True
和continue
之间永久循环。您必须在此处使用异步队列,并在等待任务可用时使用yield
:http://www.tornadoweb.org/en/stable/queues.html#tornado.queues.Queue