{py是一个新的异步编程教程。在
我运行了页面上给出的程序:
from gevent import monkey; monkey.patch_all()
from time import sleep
from bottle import route, run
@route('/stream')
def stream():
yield 'START'
sleep(3)
yield 'MIDDLE'
sleep(5)
yield 'END'
run(host='0.0.0.0', port=8080, server='gevent')
当我访问URL http://localhost:8080/stream
,打印START
,然后是MIDDLE
和{
根据文件
monkey patching enables gevent to prevent Python’s blocking APIs (and functions like time.sleep()) from blocking the current thread, and passes the CPU to the next greenlet instead.
但是,当我修改上面的代码以打印当前的greenlet信息时,我得到了用于所有三个yield
语句的相同greenlet实例。在
控制台输出:
<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>
<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>
<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>
根据bottlepy文档,每次时间。睡觉()已执行?
此外,当我运行类似的程序而不使用gevent和monkey patching时,如下所示:
from time import sleep
from bottle import route, run
@route('/stream')
def stream():
yield 'START \n'
sleep(3)
yield 'MIDDLE \n'
sleep(5)
yield 'END'
run(host='0.0.0.0', port=8080)
我得到了和以前一样的回答(开始后是中间,结束时间是3秒和5秒),与瓶装医生的评论相反,下面是黑体字:
If you run this script and point your browser to http://localhost:8080/stream, you should see START, MIDDLE, and END show up one by one (rather than waiting 8 seconds to see them all at once).
我是不是少了点什么?在
不,恐怕那里的药检有点混乱。在
为每个传入的HTTP请求生成一个新的greenlet。然后生成的greenlet从头到尾处理整个请求。如果这个greenlet产生(显式或隐式),那么另一个greenlet可以自由地做一些工作(大概是处理其他一些HTTP请求)。在
当您调用monkeypatched
time.sleep
时,正在处理HTTP请求的greenlet被挂起,从而产生任何其他活动的greenlet(如果有)。当time.sleep
返回时(在指定的秒数之后),将唤醒先前为您的请求提供服务的greenlet,并从sleep
调用之后恢复运行。在希望有帮助!在
2个答案:
相关问题 更多 >
编程相关推荐