zoukankan      html  css  js  c++  java
  • 理解twisted中的reactor和deferred(一)

    Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理。

    简单讲,当我们需要执行一个耗时操作,比如下载某个大图片,此时用twisted的异步http请求,会给我们返回一个Deferred对象,让我们可以不用在这等图片下载完成,当前线程不会阻塞,而是可以去处理别的逻辑。twisted有一个底层event loop(类似tornado ioloop)处理线程),等图片下载完成后,会去自动触发Deferred的回调操作,这个细节我们不需要操作,我们要做的,就是添加这个回调逻辑,也就是常说的注册回调。(摘自:https://www.cnblogs.com/mactec/p/9850665.html

    实例代码(可在pycharm中运行):

    from twisted.internet import reactor, defer
    
    def getDummyData(inputData):
        """
        This function is a dummy which simulates a delayed result and
        returns a Deferred which will fire with that result. Don't try too
        hard to understand this.
        """
        print('getDummyData called')
        deferred = defer.Deferred()
        # simulate a delayed result by asking the reactor to fire the
        # Deferred in 2 seconds time with the result inputData * 3
        reactor.callLater(2, deferred.callback, inputData * 3) # 表示2秒后执行Deferred的回调函数,回调函数的参数是第三个参数    
        return deferred
    
    def cbPrintData(result):
        """
        Data handling function to be added as a callback: handles the
        data by printing the result
        """
        print('Result received: {}'.format(result))
    
    deferred = getDummyData(3)
    deferred.addCallback(cbPrintData)
    
    # manually set up the end of the process by asking the reactor to
    # stop itself in 4 seconds time
    reactor.callLater(4, reactor.stop)  # 4秒后停止reactor
    # start up the Twisted reactor (event loop handler) manually
    print('Starting the reactor')
    reactor.run()
    

    结果如下:

  • 相关阅读:
    三次请求(读-改-读)引出nibernate 一级缓存
    算法竞赛入门经典第一、二章摘记
    uva 10905 Children's Game
    uva 11205 The broken pedometer
    uva 10160 Servicing stations
    uva 208 Firetruck
    uva 167 The Sultan's Successors
    zoj 1016 Parencodings
    uva 307 Sticks
    uva 216 Getting in Line
  • 原文地址:https://www.cnblogs.com/WalkOnMars/p/11927096.html
Copyright © 2011-2022 走看看