同步与异步IO

演示代码:

 1 # tornado 的HTTP客户端类
 2 from tornado.httpclient import HTTPClient
 3 from tornado.httpclient import AsyncHTTPClient
 4 import time
 5 
 6 
 7 def synchronous_visit():
 8     http_client = HTTPClient()
 9     response = http_client.fetch("https://www.baidu.com/")  # 阻塞,直到该网页访问完成
10     print(response.body)
11 
12 
13 def handle_response(response):
14     print(response.body)
15 
16 
17 def asynchronous_visit():
18     http_client = AsyncHTTPClient()
19     http_client.fetch("https://www.baidu.com", callback=handle_response)

调用代码:

1 synchronous_visit()

结果:

  

  HTTPClient 的 fetch 函数会阻塞,直到对网页的访问成功。执行速度取决于网速与响应速度。

调用代码:

1 asynchronous_visit()
2 print("进入等待...")
3 time.sleep(10)

结果:

  

  这里 AsyncHTTPClient 的fecth函数是不会阻塞的,callback指定的函数,fecth函数执行之后将response传给它,调用执行。

 

posted @ 2018-06-11 10:46  巴蜀秀才  阅读(93)  评论(0编辑  收藏  举报