协程,又称微线程,纤程。英文名Coroutine。
1 2 3 4 5 6 7 8 9
| def A(): print '1' print '2' print '3'
def B(): print 'x' print 'y' print 'z'
|
假设由协程执行,在执行A的过程中,可以随时中断,去执行B,B也可能在执行过程中中断再去执行A,结果可能是:
python 3协程
1 2 3 4 5 6 7 8 9 10 11 12
| import asyncio
async def request(url): print("正在请求的url是", url) print("请求成功", url)
c = request("www.baidu.com")
loop = asyncio.get_event_loop()
loop.run_until_complete(c)
|
显示结果:
1 2
| 正在请求的url是 www.baidu.com 请求成功 www.baidu.com
|
协程task使用
1 2 3 4 5 6
| loop = asyncio.get_event_loop()
task = loop.create_task(c) print(task) loop.run_until_complete(c)
|
协程future
1 2 3 4 5 6
| loop = asyncio.get_event_loop() task = asyncio.ensure_future(c) print(task) loop.run_until_complete(task) print(task)
|
使用回调
1 2 3 4 5 6 7 8 9 10 11
| def callback_func(task): print(task.result())
loop = asyncio.get_event_loop() task = asyncio.ensure_future(c)
task.add_done_callback(callback_func) loop.run_until_complete(task)
|
1 2 3
| 正在请求的url是 www.baidu.com 请求成功 www.baidu.com www.baidu.com
|
多任务异步协程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import asyncio import time
async def request(url): print("正在下载", url) await asyncio.sleep(2) print(url, "下载完毕")
urls = [ 'www.baidu.com', 'www.sogou.com', 'www.douban.com' ] stasks = [] for url in urls: c = request(url) task = asyncio.ensure_future(c) stasks.append(task) start = time.time() loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(stasks)) print(time.time() - start)
|