2016-03-07 130 views
1
theQueue = tornado.queues.Queue() 
theQueue.put_nowait('http://www.baidu.com') 
theQueue.put_nowait('http://www.google.com') 
theQueue.put_nowait('http://cn.bing.com/') 

@tornado.gen.coroutine 
def Test1(): 
    def cb(response): 
     print str(response) 

    while True: 
     item = yield theQueue.get() 
     print item 
     tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True) 
     tmp.fetch(item,callback=cb) 

@tornado.gen.coroutine 
def Test2(): 
    while True: 
     item = yield theQueue.get() 
     print item 
     tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True) 
     response = yield tmp.fetch(item) 
     print str(response) 

#Test1() 
Test2() 
tornado.ioloop.IOLoop.instance().start() 

蟒2.6和4.2龍捲風
在功能測試1,它將首先打印出3項,然後打印3級的響應。
但是在Test2中,它會打印項目並且它是一個接一個的響應。龍捲風異步HTTP客戶塊

我很困惑,爲什麼Test2不是異步?

回答

1

Test2()是異步的,但採用不同的方式,協程的方式。

Tornado的協同程序在它遇到yield關鍵字時暫停,等待異步進程(在您的情況下,通過http客戶端請求網頁)完成。 當前協程暫停時,龍捲風將切換到其他可用協程。

使用協程,您的代碼看起來是同步的,並且「同步運行」(如果只有一個協程)。

您可以輕鬆地測試龍捲風的協程的異步功能,通過使用兩個或更多conroutines:

@tornado.gen.coroutine 
def Test2(): 
    while True: 
     item = yield theQueue.get() 
     print 'Test2:', item 
     tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True) 
     response = yield tmp.fetch(item) 
     print 'Test2:', str(response) 

# Write another test function called `Test3` and do the exactly same thing with Test2. 
@tornado.gen.coroutine 
def Test3(): 
    while True: 
     item = yield theQueue.get() 
     print 'Test3:', item 
     tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True) 
     response = yield tmp.fetch(item) 
     print 'Test3:', str(response) 

Test2() 
Test3() 
tornado.ioloop.IOLoop.instance().start() 

你會看到的Test2和Test3的同時運行(但不是真的)在這個例子中。

在不同的例程之間切換來執行併發操作的能力,這就是協同異步的含義。

+0

在我的情況下,該隊列有很多項目,如果我使用yield,我需要創建多個Test2? –

+0

@JianNiu嘗試調用'tornado.ioloop.IOLoop.current()。spawn_callback(Test2)'多次,這將在後臺產生多協程。相關文檔:http://www.tornadoweb.org/en/stable/guide/coroutines.html#running-in-the-background – piglei