异步IO编程

来源:互联网 发布:淘宝一元起拍在哪里 编辑:程序博客网 时间:2024/06/06 00:52
import asyncioimport threading#异步IO编程:# asyncio 提供了完善的异步 IO 支持;# 异步操作需要在 coroutine 中通过 yield from 完成;# 多个 coroutine 可以封装成一组 Task 然后并发执行。@asyncio.coroutinedef hello():    print('hello world threadId:%s' % threading.current_thread())    r = yield from asyncio.sleep(2)    print('hello again threadId:%s' % threading.current_thread())loop = asyncio.get_event_loop()tasks = [hello(),hello(),hello(),hello(),hello()]loop.run_until_complete(asyncio.wait(tasks))loop.close()#将sleep真正替换成网络任务@asyncio.coroutinedef wget(host):    print('wget %s...' % host)    reader, writer = yield from  asyncio.open_connection(host, 80)    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()#3.5以后新语法#请注意,async 和 await 是针对 coroutine 的新语法,要使用新的语法,#只需要做两步简单的替换:#1. 把@asyncio.coroutine 替换为 async;#2. 把 yield from 替换为 await。#让我们对比一下上一节的代码:# @asyncio.coroutine# def hello():#     print("Hello world!")#     r = yield from asyncio.sleep(1)#     print("Hello again!")#用新语法重新编写如下:# from asyncio import async,await# async def hello2():#     print("Hello world!")#     r = await asyncio.sleep(1)#     print("Hello again!")    #剩下的代码保持不变。
原创粉丝点击