2017-07-25 84 views
0

我需要在我的web應用程序中使用異步子進程鎖。 我寫入下一個代碼:什麼是平均收益率無(tornado.gen.moment)

r = redis.Redis('localhost') 
pipe = r.pipeline() 
is_locked = False 
while not is_locked: 
    try: 
     pipe.watch(lock_name) 
     current_locked = int(pipe.get(lock_name)) 

     if current_locked == 0: 
      pipe.multi() 
      pipe.incr(lock_name) 
      pipe.execute() 
      is_locked = True 
     else: 
      yield None 
    except redis.WatchError: 
     yield None 
return True 

在文檔writen該tornado.gen.moment(yield None因爲版本4.5)是可被產生,以允許IOLoop爲一次迭代運行的特殊對象。怎麼運行的?它是否與其他Feature對象(來自其他請求)的下一次迭代?是否正確yield None用法?

+0

的cource,它在一個功能裝飾tornado.gen.coroutine – COUNTERKILL

回答

2

gen.moment剛剛解決將來的對象通過回調添加到ioloop中。這允許運行一個ioloop迭代。

yield None在協程gen.Runner中使用convert_yielded轉換爲gen.moment

的ioloop(基本上while True)在每次迭代做這樣的事情:計劃與ioloop的add_callbackadd_callback_from_signal

  • 運行回調

    1. 運行回調安排與ioloop的add_timeout

    2. 輪詢fd事件(例如,等待文件描述符準備好寫入或讀取)。當然不阻止ioloop投票已經超時。準備FDS

    因此獲得的點yield gen.moment

  • 運行處理程序將允許做上文對於一次(一次迭代)的事情。

    舉一個例子,讓我們安排異步任務 - 需要運行ioloop的httpclient獲取完成。另一方面也會有阻止功能(time.sleep)。

    import time 
    from tornado import gen 
    from tornado.ioloop import IOLoop 
    from tornado.httpclient import AsyncHTTPClient 
    
    
    @gen.coroutine 
    def fetch_task(): 
        client = AsyncHTTPClient() 
        yield client.fetch('http://google.com') 
        print('fetch_task finished') 
    
    
    @gen.coroutine 
    def blocking(): 
        start_time = time.time() 
        counter = 1 
        while True: 
         time.sleep(5) 
         print('blocking for %f' % (time.time() - start_time)) 
         yield gen.moment 
         print('gen.moment counter %d' % counter) 
         counter += 1 
    
    
    @gen.coroutine 
    def main(): 
        fetch_task() 
        yield blocking() 
    
    
    IOLoop.instance().run_sync(main) 
    

    觀察:

    • 沒有yield gen.moment,該fetch_task將無法​​完成
    • 增長time.sleep /減小值不會影響ioloop所需的迭代次數爲fetch_task到完成。這也意味着AsyncHTTPClient.fetchN + 1(gen.moments +任務調度)與ioloop的交互(處理回調,輪詢fd,處理事件)。
    • gen.moment並不總是意味着,其他任務將完成,而他們有機會向完整性靠近一步。
  • +0

    非常感謝! – COUNTERKILL