异步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!") #剩下的代码保持不变。
阅读全文
0 0
- 伪异步IO编程
- 异步IO编程
- Linux 异步IO 读写编程
- linux异步IO编程实例分析
- linux异步IO编程实例分析
- linux异步IO编程实例分析
- linux异步IO编程实例分析
- linux异步IO编程实例分析
- 《Windows核心编程》之“同步IO和异步IO”
- win32串口同步编程、异步编程(重叠IO)
- 异步IO
- 异步IO
- 异步IO
- 异步IO
- 异步io
- 异步IO
- 异步 IO
- 异步IO
- 【Nova】nova-network网络模型之flatdhcp网络-代码学习3
- Java中的抽象类和接口
- python单例模式
- tcpdump 简介
- Android基础:API对应的版本号
- 异步IO编程
- 模板方法(template method)c++版本
- HDU
- 计算模型是否与人类对象感知有系统的不同?
- Oil Deposits (dfs)深度搜索
- python3 自带常用函数
- 确定比赛名次 HDU
- Error:Execution failed for task ':app:transformClassesWithDexForDebug'解决办法
- hihocoder 1094 : Lost in the City