python异步IO-asyncio

参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432090954004980bd351f2cd4cc18c9e6c06d855c498000

总结:

   asynico 提供了完善的异步IO支持、异步操作(有的是异步操作,不是协程)需要在 coroutine 里通过 yield from 语句引入、多个 coroutine 可以封装成一组Task实现并发执行

一、  asyncio的编程模型就是一个消息循环,我们从 asyncio 中直接取一个 eventloop 的引用,然后把要执行的协程扔到这个引用里面执行,这样就实现了异步IO

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 (事件循环)里面执行

  hello()会首先打印出‘Hello world!’, rield form  语句可以让我们方便的调用 generator ,同时 asyncio.sleep(1) 也是一个 coroutine ,所以线程并不会等待它执行完,而是直接中断执行下一个消息循环(即处理其他的协程?),当这条语句执行完毕后,消息循环会通过 yield from 返回值(实际是None),然后再继续执行下一条语句

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

  让我疑惑的一点是,上述并发给我的感觉是两个 coroutine 之间执行进度是互不影响的,即Hello world! 与Hello again!之间并不会等待1秒,但从结果来看并不是这样

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

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

二、  用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
...

  

  

猜你喜欢

转载自www.cnblogs.com/Gaoqiking/p/10625341.html
今日推荐