本文共 3721 字,大约阅读时间需要 12 分钟。
import asyncio@asyncio.coroutinedef hello(): print("Hello world!") # 异步调用asyncio.sleep(1): r = yield from asyncio.sleep(1) print("Hello again!")# 获取EventLoop:loop = asyncio.get_event_loop()# 执行coroutineloop.run_until_complete(hello())loop.close()
@asyncio.coroutine把一个generator标记为coroutine类型,然后,我们就把这个coroutine EventLoop扔到coroutineEventLoop中执行。
hello()会首先打印出Hello world!,然后,yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。把asyncio.sleep(1)看成是一个耗时1秒的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine了,因此可以实现并发执行。
我们用Task封装两个coroutine试试:import threadingimport asyncio@asyncio.coroutinedef hello(): print('Hello world! (%s)' % threading.currentThread()) yield from asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread())loop = asyncio.get_event_loop()tasks = [hello(), hello()]loop.run_until_complete(asyncio.wait(tasks))loop.close()
观察执行过程:
Hello world! (<_MainThread(MainThread, started 140735195337472)>)Hello world! (<_MainThread(MainThread, started 140735195337472)>)(暂停约1秒)Hello again! (<_MainThread(MainThread, started 140735195337472)>)Hello again! (<_MainThread(MainThread, started 140735195337472)>)
由打印的当前线程名称可以看出,两个coroutine是由同一个线程并发执行的。
如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页:import asyncio@asyncio.coroutinedef wget(host): print('wget %s...' % host) connect = asyncio.open_connection(host, 80) reader, writer = yield from connect header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host writer.write(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() if line == b'\r\n': break print('%s header > %s' % (host, line.decode('utf-8').rstrip())) # Ignore the body, close the socket writer.close()loop = asyncio.get_event_loop()tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]loop.run_until_complete(asyncio.wait(tasks))loop.close()
执行结果如下:
wget www.sohu.com...wget www.sina.com.cn...wget www.163.com...(等待一段时间)(打印出sohu的header)www.sohu.com header > HTTP/1.1 200 OKwww.sohu.com header > Content-Type: text/html...(打印出sina的header)www.sina.com.cn header > HTTP/1.1 200 OKwww.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT...(打印出163的header)www.163.com header > HTTP/1.0 302 Moved Temporarilywww.163.com header > Server: Cdn Cache Server V2.0...
可见3个连接由一个线程通过coroutine并发完成。
asyncio提供了完善的异步IO支持;异步操作需要在coroutine中通过yield from完成;
多个coroutine可以封装成一组Task然后并发执行。
测试与说明:
import asyncio@asyncio.coroutinedef baby(num): print('baby %s sleep' % num) yield from asyncio.sleep(1) print('baby %s week up' % num)loop = asyncio.get_event_loop()tasks = [baby(1), baby(2), baby(3)]loop.run_until_complete(asyncio.wait(tasks))loop.close()
输出:
baby 1 sleepbaby 2 sleepbaby 3 sleepbaby 1 week upbaby 2 week upbaby 3 week up
yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。
转载于:https://blog.51cto.com/445153/2147254