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
代码示例
# -*- 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()
执行结果