Python编程:trio模块异步/等待本地I/O库
【摘要】 github: https://github.com/python-trio/trio 文档: https://trio.readthedocs.io/en/latest/tutorial.html
An async/await-native I/O library for humans and snake people
安装
pip install trio
1...
github: https://github.com/python-trio/trio
文档: https://trio.readthedocs.io/en/latest/tutorial.html
An async/await-native I/O library for humans and snake people
安装
pip install trio
- 1
代码示例
# -*- coding: utf-8 -*-
import trio
import time
# 计时器
def timer(func): def inner(*args): start = time.time() ret = func(*args) end = time.time() print("{} time: {}".format(func.__name__, end - start)) return ret return inner
############## 同步执行 ######################
def sync_add(x, y): time.sleep(2) print("sync_add: {}".format(x + y))
def sync_multiply(x, y): time.sleep(2) print("sync_multiply: {}".format(x * y))
@timer
def sync_func(): sync_add(1, 1) sync_multiply(1, 1)
sync_func()
############## 异步执行 ######################
async def async_add(x, y): await trio.sleep(2) print("async_add: {}".format(x + y))
async def async_multiply(x, y): await trio.sleep(2) print("async_multiply: {}".format(x * y))
async def async_func(): async with trio.open_nursery() as nursery: nursery.start_soon(async_add, 1, 1) nursery.start_soon(async_multiply, 1, 1)
@timer
def run_async(): trio.run(async_func)
run_async()
- 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
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
执行结果
sync_add: 2
sync_multiply: 1
sync_func time: 4.00608491897583
async_multiply: 1
async_add: 2
run_async time: 2.0082740783691406
- 1
- 2
- 3
- 4
- 5
- 6
- 7
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/88992809
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)