tornado实现异步非阻塞

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()


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值