参考链接:

  asyncio:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432090954004980bd351f2cd4cc18c9e6c06d855c498000

  async与await:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00144661533005329786387b5684be385062a121e834ac7000

总结:

asynico 提供了完善的异步IO支持、异步操作(有的是异步操作,不是协程)需要在 coroutine 里通过 yield from 语句引入、多个 coroutine

asyncio 提供的 @asyncio.coroutine 可以把一个 generator 标记为 coroutine 类型,然后在 coroutine 内部用 yield from 调用另一个 coroutine 实现异步操作

一、  asyncio的编程模型就是一个消息循环,我们从 asyncio 中直接取一个 eventloop



import asyncio

@asyncio.coroutine
def hello():
    print('Hello world!')
    #异步调用asynico.sleep(1)
    r=yield from asyncio.sleep(1)
    print('Hello again!')

#获取eventloop
loop=asyncio.get_event_loop()
#执行coroutine(协程)
loop.run_until_complete(hello())
loop.close()



@asyncio.coroutine 将一个 generator 标记为 coroutine 类型,然后将这个 coroutine 放到 eventloop

rield form  语句可以让我们方便的调用 generator ,同时 asyncio.sleep(1) 也是一个 coroutine ,所以线程并不会等待它执行完,而是直接中断执行下一个消息循环(即处理其他的协程?),当这条语句执行完毕后,消息循环会通过 yield from

asyncio.sleep(1) 看作为耗时一秒的IO操作,在此期间,线程并不会等待这个 coroutine ,而是转而执行 eventloop 中其他的 coroutine

coroutine



Hello world!
【中间暂停1秒】
Hello again!



eventloop 中只有一个协程(可不是说 asyncio.sleep(1) 也是一个 coroutine 吗?,难道是根据 loop.run_until_complete(hello()) 来判定只有一个协程是hello()吗?)嗯,好想是这样的,因为后面向 eventloop

 

二、  用Task来封装两个 coroutine



import threading
import asyncio

@asyncio.coroutine
def 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

我不清楚这个task是怎样使用的,但是从上面结果来看,很容易就可以看出两个hello(虽然他们是一模一样的两个)是交替运行的

如果把 asyncio.sleep() 换成真正的IO操作,则多个 coroutine

 

三、通过展示一个用 asyncio的异步网络连接来获取sina、sohu和163的网站首页的例子直观的展现了三个连接可以死并发(即交替)执行的。



import asyncio

@asyncio.coroutine
def 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()))
        #忽略body,关闭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 OK
www.sohu.com header > Content-Type: text/html
...
(打印出sina的header)
www.sina.com.cn header > HTTP/1.1 200 OK
www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT
...
(打印出163的header)
www.163.com header > HTTP/1.0 302 Moved Temporarily
www.163.com header > Server: Cdn Cache Server V2.0
...



 

四、  

async 与 await 是python3.5引入的新语法,为了让 coroutine 的语法更简介,用来代替 @asyncio.coroutine 和 yield from

请注意, async 和 await 是针对 coroutine

  1. 把 @asyncio.coroutine 替换为 async
  2. 把 yield from 替换为 await