最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python?tornado協程調度原理示例解析

 更新時間:2023年09月08日 09:34:43   作者:菜皮日記  
這篇文章主要為大家介紹了python?tornado協程調度原理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

tornado 的協程實現原理

本文討論 tornado 的協程實現原理,簡單做了一份筆記。

首先看一段最常見的 tornado web 代碼:

import tornado
import tornado.web
import tornado.gen
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient
class GenHandler(tornado.web.RequestHandler):
    @coroutine
    def get(self):
        url = 'http://www.baidu.com'
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url)
        yield tornado.gen.sleep(5)
        self.write(response.body)
class MainHanler(tornado.web.RequestHandler):
    def get(self):
        self.write('root')
if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHanler),
        (r"/gen_async/", GenHandler),
    ], autoreload=True)
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

其中最后一行代碼 tornado.ioloop.IOLoop.current().start() 啟動服務。

帶著幾個問題往下看:

  • 知道 yield 可以暫存執(zhí)行狀態(tài),等「合適的時機」重新恢復執(zhí)行,那么保存的狀態(tài)到哪去了?
  • 上一個問題中「合適的時機」是到底是什么時候?
  • 繼續(xù)接上一個問題,具體是怎么恢復執(zhí)行的?

IOLoop 類相當于是對多路復用的封裝,起到事件循環(huán)的作用,調度整個協程執(zhí)行過程。

查看 IOLoop 的源碼,可以看到 IOLoop 繼承自 Configurable,PollIOLoop 又繼承自 IOLoop。當 IOLoop 啟動時,會確定使用哪一種多路復用方式,epoll、kqueue 還是 select?

# IOLoop 類
# IOLoop 中的 configurable_default 方法是重寫 Configurable 的
# 這里會確定使用哪種多路復用方式
@classmethod
def configurable_default(cls):
    if hasattr(select, "epoll"):
        from tornado.platform.epoll import EPollIOLoop
        return EPollIOLoop
    if hasattr(select, "kqueue"):
        # Python 2.6+ on BSD or Mac
        from tornado.platform.kqueue import KQueueIOLoop
      return KQueueIOLoop
    from tornado.platform.select import SelectIOLoop
  return SelectIOLoop
# PollIOLoop類
def initialize(self, impl, time_func=None, **kwargs):
    super(PollIOLoop, self).initialize(**kwargs)
    self._impl = impl
    if hasattr(self._impl, 'fileno'):
        set_close_exec(self._impl.fileno())
    self.time_func = time_func or time.time
    self._handlers = {}
    self._events = {}
    self._callbacks = []
    self._callback_lock = threading.Lock()
    self._timeouts = []
    self._cancellations = 0
    self._running = False
    self._stopped = False
    self._closing = False
    self._thread_ident = None
    self._blocking_signal_threshold = None
    self._timeout_counter = itertools.count()

    # Create a pipe that we send bogus data to when we want to wake
    # the I/O loop when it is idle
    self._waker = Waker()
    self.add_handler(self._waker.fileno(),
                     lambda fd, events: self._waker.consume(),
                     self.READ)

def add_handler(self, fd, handler, events):
    fd, obj = self.split_fd(fd)
    self._handlers[fd] = (obj, stack_context.wrap(handler))
    self._impl.register(fd, events | self.ERROR)

def update_handler(self, fd, events):
    fd, obj = self.split_fd(fd)
    self._impl.modify(fd, events | self.ERROR)

def remove_handler(self, fd):
    fd, obj = self.split_fd(fd)
    self._handlers.pop(fd, None)
    self._events.pop(fd, None)
    try:
        self._impl.unregister(fd)
    except Exception:
        gen_log.debug("Error deleting fd from IOLoop", exc_info=True)

PollIOLoop 中 initalize 方法中調用 add_handler 方法,注冊對應事件的處理函數,如 socket 可讀時,回調哪個函數去處理。

IOLoop 和協程之間的信使:Future

class Future(object):
    def __init__(self):
        self._result = None
        self._exc_info = None
        self._callbacks = []
        self.running = True
        
    def set_result(self, result):
        ...
        
    def set_exc_info(self, exce_info):
        ...
        
    def result(self):
        ...
    
    def exc_info(self):
        ...
        
    def add_done_callback(self, callback):
        self._callbacks.append(callback)

Future 對象起到“占位符”的作用,協程的執(zhí)行結果會通過 set_result 方式寫入其中,并調用通過 add_done_callback 設置的回調。

恢復喚醒協程的 Runner

class Runner(object):
    def __init__(self, gen, result_future, first_yielded):
        self.gen = gen
        self.result_future = result_future
        self.future = _null_future
        self.yield_point = None
        self.pending_callbacks = None
        self.results = None
        self.running = False
        self.finished = False
        self.had_exception = False
        self.io_loop = IOLoop.current()
        self.stack_context_deactivate = None
        # 上面一堆不需要看的初始化
        if self.handle_yield(first_yielded):
            gen = result_future = first_yielded = None
            self.run()
     
    
    def handle_yield(self, yielded):

        self.future = convert_yielded(yielded)

        if self.future is moment:
            self.io_loop.add_callback(self.run)
            return False
        elif not self.future.done():
            def inner(f):
                # Break a reference cycle to speed GC.
                f = None
                self.run()
            self.io_loop.add_future(
                self.future, inner)
            return False
        return True
    
    def run(self):
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if not future.done():
                    return
                self.future = None
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        self.had_exception = True
                        exc_info = sys.exc_info()
                    future = None
  
                    yielded = self.gen.send(value)

                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    if self.pending_callbacks and not self.had_exception:
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    future_set_result_unless_cancelled(self.result_future,
_value_from_stopiteration(e))
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                except Exception:
                    # 一些結束操作
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False

協程每生成一個 Future,都會生成對應的一個 Runner,并將 Future 初始化注入都其中。Runner 的 run 方法中,通過 self.gen.send(Future) 來啟動 Future,當 Future 完成時,將其設置成 done,并回調其預設的 callback。

第一個問題:協程的狀態(tài)保存到哪去了

IOLoop 中通過 add_future 調用實現類 PollIOLoop 中的 add_callback 方法,其中通過 functools 生成偏函數,放入 _callbacks 列表,等待被回調執(zhí)行。

# IOLoop 的add_future
def add_future(self, future, callback):
    """Schedules a callback on the ``IOLoop`` when the given
    `.Future` is finished.

    The callback is invoked with one argument, the
    `.Future`.
    """
    assert is_future(future)
    callback = stack_context.wrap(callback)
    future.add_done_callback(
        lambda future: self.add_callback(callback, future))

# PollIOLoop 的add_callback
def add_callback(self, callback, *args, **kwargs):
        if thread.get_ident() != self._thread_ident:
            with self._callback_lock:
                if self._closing:
                    return
                list_empty = not self._callbacks
                self._callbacks.append(functools.partial(
                    stack_context.wrap(callback), *args, **kwargs))
                if list_empty:
                    self._waker.wake()
        else:
            if self._closing:
                return
            self._callbacks.append(functools.partial(
                stack_context.wrap(callback), *args, **kwargs))

第二個問題:「合適的時機」是什么?

IOLoop 實際上就是對多路復用的封裝,當底層 epoll_wait 事件發(fā)生時,即會通知 IOLoop 主線程。

這一段是 IOLoop 中等待多路復用的事件,以及處理事件。

try:
    # 等待事件
      event_pairs = self._impl.poll(poll_timeout)
except Exception as e:
      print("wait fail")
      if errno_from_exception(e) == errno.EINTR:
          continue
      else:
          raise
if self._blocking_signal_threshold is not None:
                    signal.setitimer(signal.ITIMER_REAL,
                                     self._blocking_signal_threshold, 0)
# 處理事件
self._events.update(event_pairs)
while self._events:
    fd, events = self._events.popitem()
    try:
        fd_obj, handler_func = self._handlers[fd]
        handler_func(fd_obj, events)
    except (OSError, IOError) as e:
        if errno_from_exception(e) == errno.EPIPE:
            pass
        else:
            self.handle_callback_exception(self._handlers.get(fd))
    except Exception:
        self.handle_callback_exception(self._handlers.get(fd))
fd_obj = handler_func = None

第三個問題:具體是怎么恢復的。

Runner 通過不斷 check Future 的狀態(tài),最后調用 callback 來返回結果。

總結

首先 tornado 對多路復用系統(tǒng)調用做了封裝,來實現非阻塞 web 服務。

其次 tornado 通過 yield+Future+Runner 實現了生成 Future,Runner 監(jiān)控結果,回調 callback 來實現協程的執(zhí)行。

參考:

http://www.fzitv.net/python/2976505cr.htm

http://www.fzitv.net/article/132918.htm

tornado的事件循環(huán)機制

以上就是python tornado協程調度原理示例解析的詳細內容,更多關于python tornado協程調度的資料請關注腳本之家其它相關文章!

相關文章

  • Python3中處理和操作純文本文件的詳細教程

    Python3中處理和操作純文本文件的詳細教程

    本教程將簡要描述 Python 能夠處理的一些文件格式,在簡要介紹這些文件格式之后,你將學習如何在 Python 3 中打開、讀取和寫入文本文件,完成后,你將能夠處理 Python 中的任何純文本文件,需要的朋友可以參考下
    2024-06-06
  • Python實現訪問者模式詳情

    Python實現訪問者模式詳情

    這篇文章主要介紹了Python實現訪問者模式詳情,訪問者模式,指作用于一個對象結構體上的元素的操作。訪問者可以使用戶在不改變該結構體中的類的基礎上定義一個新的操作,下文更多相關資料,需要的朋友可以參考下
    2022-03-03
  • Python列表list解析操作示例【整數操作、字符操作、矩陣操作】

    Python列表list解析操作示例【整數操作、字符操作、矩陣操作】

    這篇文章主要介紹了Python列表list解析操作,結合實例形式分析了Python列表針對整數、字符及矩陣的解析操作實現技巧,需要的朋友可以參考下
    2017-07-07
  • Python 數據結構之堆棧實例代碼

    Python 數據結構之堆棧實例代碼

    這篇文章主要介紹了Python 數據結構之堆棧實例代碼的相關資料,需要的朋友可以參考下
    2017-01-01
  • 90行Python代碼開發(fā)個人云盤應用

    90行Python代碼開發(fā)個人云盤應用

    這篇文章主要介紹了90行Python代碼開發(fā)個人云盤應用,幫助大家更好的理解和學習python,感興趣的朋友可以了解下
    2021-04-04
  • 基于Python+ECharts實現實時數據大屏

    基于Python+ECharts實現實時數據大屏

    文章介紹了如何使用Python爬蟲和ECharts構建實時數據大屏,通過自動化數據采集和動態(tài)數據展示,提高決策效率,關鍵步驟包括爬蟲開發(fā)、ECharts可視化和系統(tǒng)集成,同時提供了常見問題的解決方案和進階方向,需要的朋友可以參考下
    2026-01-01
  • pythotn條件分支與循環(huán)詳解(3)

    pythotn條件分支與循環(huán)詳解(3)

    這篇文章主要介紹了Python條件分支和循環(huán)用法,結合實例形式較為詳細的分析了Python邏輯運算操作符,條件分支語句,循環(huán)語句等功能與基本用法,需要的朋友可以參考下
    2021-08-08
  • Flask框架實現的前端RSA加密與后端Python解密功能詳解

    Flask框架實現的前端RSA加密與后端Python解密功能詳解

    這篇文章主要介紹了Flask框架實現的前端RSA加密與后端Python解密功能,結合實例形式詳細分析了flask框架前端使用jsencrypt.js加密與后端Python解密相關操作技巧,需要的朋友可以參考下
    2019-08-08
  • 詳解Python如何實現批量為PDF添加水印

    詳解Python如何實現批量為PDF添加水印

    我們有時候需要把一些機密文件發(fā)給多個客戶,為了避免客戶泄露文件,會在機密文件中添加水印。本文將利用Python實現批量為PDF添加水印,需要的可以參考一下
    2022-05-05
  • 利用Python制作一個MOOC公開課下載器

    利用Python制作一個MOOC公開課下載器

    為了幫助大家更好地在假期內卷,本文將利用Python制作一個中國大學MOOC的公開課下載器。文中的示例代碼講解詳細,感興趣的小伙伴可以學習一下
    2022-03-03

最新評論

沾益县| 武隆县| 阜南县| 容城县| 井陉县| 肇东市| 铁岭县| 公安县| 陆良县| 滨州市| 海林市| 武城县| 景谷| 桓台县| 抚宁县| 肇州县| 黄龙县| 镇雄县| 成都市| 贡觉县| 盐源县| 高邑县| 海盐县| 怀仁县| 金沙县| 石狮市| 军事| 阜阳市| 海伦市| 高阳县| 齐河县| 阳曲县| 儋州市| 徐州市| 静乐县| 集贤县| 焉耆| 新营市| 澄江县| 沽源县| 松原市|