Mar*_*cha 5 python tornado nonblocking
我想问一下tornado.concurrent.run_on_executor(以后只是run_on_executor)如何工作,因为我可能不明白如何运行同步任务来阻止主IOLoop.
run_on_executor我发现所有使用的例子都只是time用来阻止循环.使用time模块它工作正常,但当我尝试使用时run_on_executor,任务阻止IOLoop.我能够看到应用程序使用多个线程,但它仍然阻塞.
我想用于使用run_on_executor散列密码bcrypt,但是用这个计算代替它以获得一些额外的测试时间.
在这里,我有一个小应用程序,以证明我的困惑.
from tornado.options import define, options
import tornado.web
import tornado.httpserver
from tornado import gen
from tornado.concurrent import run_on_executor
import tornado.httpclient
import tornado.escape
import time
import concurrent.futures
import urllib
executor = concurrent.futures.ThreadPoolExecutor(20)
define("port", default=8888, help="run on the given port", type=int)
# Should not be blocking ?
class ExpHandler(tornado.web.RequestHandler):
_thread_pool = executor
@gen.coroutine
def get(self, num):
i = int(num)
result = yield self.exp(2, i)
self.write(str(result))
self.finish()
@run_on_executor(executor="_thread_pool")
def exp(self, x, y):
result = x ** y
return(result)
class NonblockingHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
http_client = tornado.httpclient.AsyncHTTPClient()
try:
response = yield http_client.fetch("http://www.google.com/")
self.write(response.body)
except tornado.httpclient.HTTPError as e:
self.write(("Error: " + str(e)))
finally:
http_client.close()
self.finish()
class SleepHandler(tornado.web.RequestHandler):
_thread_pool = executor
@gen.coroutine
def get(self, sec):
sec = float(sec)
start = time.time()
res = yield self.sleep(sec)
self.write("Sleeped for {} s".format((time.time() - start)))
self.finish()
@run_on_executor(executor="_thread_pool")
def sleep(self, sec):
time.sleep(sec)
return(sec)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/exp/(?P<num>[^\/]+)?', ExpHandler),
(r'/nonblocking/?', NonblockingHandler),
(r'/sleep/(?P<sec>[^\/]+)?',SleepHandler)
]
settings = dict(
debug=True,
logging="debug"
)
tornado.web.Application.__init__(self, handlers, **settings)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
io_loop = tornado.ioloop.IOLoop.instance()
io_loop.start()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
我会非常感谢任何解释,为什么ExpHandler,运行executor阻止循环.
Python(至少在CPython实现中)有一个全局解释器锁,它可以防止多个线程同时执行Python代码.特别是,在单个Python操作码中运行的任何内容都是不可中断的,除非它调用显式释放GIL的C函数.一个大的指数,一直**保持GIL,因此阻止所有其他python线程,而一个调用bcrypt()将释放GIL,以便其他线程可以继续工作.
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |