2016-08-13 99 views
0

我有一個mysterious_library,提供同步功能query_resource_for_a_long_time簡單的多線程示例與tornado.web.RequestHandler

然後,我有下面的代碼應該異步獲取資源:

import tornado.ioloop 
import tornado.web 

import threading 
from mysterious_library import query_resource_for_a_long_time, ResourceNotFoundException 

def resource_fetcher(set_status, finish): 
    try: 
     resource = query_resource_for_a_long_time() 

    except ResourceNotFoundException: 
     tornado.ioloop.IOLoop.instance().add_callback(set_status, 404) 
     tornado.ioloop.IOLoop.instance().add_callback(finish, 'not found') 

    else: 
     tornado.ioloop.IOLoop.instance().add_callback(set_status, 200) 
     tornado.ioloop.IOLoop.instance().add_callback(finish, str(resource)) 

class Handler(tornado.web.RequestHandler): 

    @tornado.web.asynchronous 
    def get(self): 
     threading.Thread(
      target=resource_fetcher, 
      args=[self.set_status, self.finish] 
     ).start() 


tornado.web.Application([ 
    (r'.*', Handler), 
]).listen(8765) 
tornado.ioloop.IOLoop.instance().start() 

然而,似乎這個過程被阻塞,直到query_resource_for_a_long_time回報,雖然功能在一個獨立的線程中運行。

我是新來的龍捲風,我想知道是否有可能同時處理這些請求。

回答

1

是,按照說明使用的ThreadPoolExecutor:

http://www.tornadoweb.org/en/stable/guide/coroutines.html#calling-blocking-functions

要知道,當你正在測試這一點,你一次只能從你的瀏覽器中運行幾個查詢:

http://www.tornadoweb.org/en/stable/faq.html#my-code-is-asynchronous-but-it-s-not-running-in-parallel-in-two-browser-tabs

...所以如果你想向自己證明你可以在Tornado中一次運行多個線程中的神祕的長時間運行的函數,請嘗試wget或curl。