python 中的run_in_executor 和 run_on_executor 实现在异步中调用阻塞函数
Posted 74 months ago python asyncio 多线程 eventloop 异步
有个挺好玩的东西 python中asyncio 有两个函数 run_in_executor 和 run_on_executor
run_on_executor 用法
##这部分懒得写demo了 随意找地方复制的 = =
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from tornado.concurrent import run_on_executor
class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(10)
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
start = time.time()
res = yield self.sleep()
self.write("when i sleep %f s" % (time.time() - start))
self.finish()
@run_on_executor
def sleep(self):
time.sleep(5)
return 5
run_in_executor 用法
class Index(basic):
async def get(self):
name = self.request.match_info.get('name', "Anonymous")
text = "Hello, " + name
loop = asyncio.get_event_loop()
print(loop.__hash__())
c = await loop.run_in_executor(None,fuck,"asasas")
return self.outJson(text=c)
def fuck(data)->str:
return data+"async!!!"
似乎差别不是很大 = =
继续折腾!