from tornado import gen # 引入协程库gen
from tornado.httpclient import AsyncHTTPClient
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
import tornado.ioloop
import tornado.web
import time,os
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello world")
class BaseHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(10)
# 下面这个采用线程池处理不会阻塞其它接口执行
# 下面的采用sleep和for循环会导致当前接口阻塞,不会阻塞其它接口
# 采用yield sleep当前接口和其它皆苦都不会阻塞
class TestHandler(BaseHandler):
@run_on_executor
def get(self):
print("start call another coroutine")
self.coroutine_visit()
print("end of outer_couroutine")
self.write("Hello world22")
# 使用gen.coroutine修饰器
def coroutine_visit(self):
# time.sleep(15)
for i in range(1000000000):
pass
# yield gen.sleep(15)
# 下面这个接口采用yield gen.sleep(100)模拟不会导致其余接口阻塞
# 下面这个接口采用time.sleep(5)和for循环会导致其余接口阻塞
class AsyncTaskHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, *args, **kwargs):
# yield 结果
response = yield self.ping('AsyncTaskHandler')
print('response', response)
self.finish('hello')
@tornado.gen.coroutine
def ping(self, url):
# gen.sleep函数可用来模拟IO等待
# yield gen.sleep(100)
# time.sleep函数是阻塞的,但不支持异步。
# time.sleep(5)
for i in range(1000000000):
pass
return 'after'
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/tes", TestHandler),
(r"/test", AsyncTaskHandler),
])
def main():
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
更多参考:
https://www.cnblogs.com/becker/p/9335136.html
线程实现并行函数
import threading
import asyncio
@asyncio.coroutine
def hello(a):
if a == 5:
return 100
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(1), hello(5)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()