1. asyncio
    2. 阅读: 127564
    3. asyncioPython 3.4版本引入的标准库,直接内置了对异步IO的支持。
    4. asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO
    5. asyncio实现Hello world代码如下:
    6. import asyncio
    7. @asyncio.coroutine
    8. def hello():
    9. print("Hello world!")
    10. # 异步调用asyncio.sleep(1):
    11. r = yield from asyncio.sleep(1)
    12. print("Hello again!")
    13. # 获取EventLoop:
    14. loop = asyncio.get_event_loop()
    15. # 执行coroutine
    16. loop.run_until_complete(hello())
    17. loop.close()
    18. @asyncio.coroutine把一个generator标记为coroutine类型,然后,我们就把这个coroutine扔到EventLoop中执行。
    19. hello()会首先打印出Hello world!,然后,yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。
    20. asyncio.sleep(1)看成是一个耗时1秒的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine了,因此可以实现并发执行。
    21. 我们用Task封装两个coroutine试试:
    22. import threading
    23. import asyncio
    24. @asyncio.coroutine
    25. def hello():
    26. print('Hello world! (%s)' % threading.currentThread())
    27. yield from asyncio.sleep(1)
    28. print('Hello again! (%s)' % threading.currentThread())
    29. loop = asyncio.get_event_loop()
    30. tasks = [hello(), hello()]
    31. loop.run_until_complete(asyncio.wait(tasks))
    32. loop.close()
    33. 观察执行过程:
    34. Hello world! (<_MainThread(MainThread, started 140735195337472)>)
    35. Hello world! (<_MainThread(MainThread, started 140735195337472)>)
    36. (暂停约1秒)
    37. Hello again! (<_MainThread(MainThread, started 140735195337472)>)
    38. Hello again! (<_MainThread(MainThread, started 140735195337472)>)
    39. 由打印的当前线程名称可以看出,两个coroutine是由同一个线程并发执行的。
    40. 如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。
    41. 我们用asyncio的异步网络连接来获取sinasohu163的网站首页:
    42. import asyncio
    43. @asyncio.coroutine
    44. def wget(host):
    45. print('wget %s...' % host)
    46. connect = asyncio.open_connection(host, 80)
    47. reader, writer = yield from connect
    48. header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    49. writer.write(header.encode('utf-8'))
    50. yield from writer.drain()
    51. while True:
    52. line = yield from reader.readline()
    53. if line == b'\r\n':
    54. break
    55. print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    56. # Ignore the body, close the socket
    57. writer.close()
    58. loop = asyncio.get_event_loop()
    59. tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
    60. loop.run_until_complete(asyncio.wait(tasks))
    61. loop.close()
    62. 执行结果如下:
    63. wget www.sohu.com...
    64. wget www.sina.com.cn...
    65. wget www.163.com...
    66. (等待一段时间)
    67. (打印出sohuheader)
    68. www.sohu.com header > HTTP/1.1 200 OK
    69. www.sohu.com header > Content-Type: text/html
    70. ...
    71. (打印出sinaheader)
    72. www.sina.com.cn header > HTTP/1.1 200 OK
    73. www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT
    74. ...
    75. (打印出163header)
    76. www.163.com header > HTTP/1.0 302 Moved Temporarily
    77. www.163.com header > Server: Cdn Cache Server V2.0
    78. ...
    79. 可见3个连接由一个线程通过coroutine并发完成。
    80. 小结
    81. asyncio提供了完善的异步IO支持;
    82. 异步操作需要在coroutine中通过yield from完成;
    83. 多个coroutine可以封装成一组Task然后并发执行。
    84. 参考源码
    85. async_hello.py
    86. async_wget.py