janus:同步异步混合队列,实现线程与asyncio代码通信

Thread-safe asyncio-aware queue for Python

分支12Tags22
文件最后提交记录最后更新时间
8 天前
1 年前
1 年前
10 年前
6 年前
10 年前
1 年前
8 年前
10 年前
1 年前
1 年前
2 个月前
1 个月前
1 年前
4 年前

======= Janus

.. image:: https://github.com/aio-libs/janus/actions/workflows/ci.yml/badge.svg :target: https://github.com/aio-libs/janus/actions/workflows/ci.yml .. image:: https://codecov.io/gh/aio-libs/janus/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/janus .. image:: https://img.shields.io/pypi/v/janus.svg :target: https://pypi.python.org/pypi/janus .. image:: https://badges.gitter.im/Join Chat.svg :target: https://gitter.im/aio-libs/Lobby :alt: 在 Gitter 上聊天

混合同步-异步队列,旨在用于经典同步(线程)代码与异步(在 asyncio 意义上)代码间的通信。

如同 Janus 神祇,该库中的队列对象具有两副面孔:同步和异步接口。

同步接口完全兼容 标准队列,异步接口遵循 asyncio 队列设计

使用说明

提供三种队列:

  • Queue
  • LifoQueue
  • PriorityQueue

每种队列都包含两个属性:sync_qasync_q

使用 sync_q 获取同步接口,使用 async_q 获取异步接口。

示例

.. code:: python

import asyncio import janus

def threaded(sync_q: janus.SyncQueue[int]) -> None: for i in range(100): sync_q.put(i) sync_q.join()

async def async_coro(async_q: janus.AsyncQueue[int]) -> None: for i in range(100): val = await async_q.get() assert val == i async_q.task_done()

async def main() -> None: queue: janus.Queue[int] = janus.Queue() loop = asyncio.get_running_loop() fut = loop.run_in_executor(None, threaded, queue.sync_q) await async_coro(queue.async_q) await fut await queue.aclose()

asyncio.run(main())

限制条件

该库采用经典的线程安全设计。此设计久经考验,但存在一些限制。

  • 当您完成对队列的使用后,必须使用 aclose() 正确关闭它。这是因为该库会创建新任务以通知其他线程。如果您未正确关闭队列,asyncio 可能会生成错误消息
  • 当按预期使用时,即用于同步代码与异步代码之间的通信时,库的性能相当出色。对于仅同步和仅异步的场景,请使用 queueasyncio queue 模块中的队列,否则 性能下降可能相当显著
  • 不能使用队列在不同的事件循环之间进行通信,因为它们像所有的 asyncio 原语一样,绑定到当前的事件循环。

开发状态为生产/稳定。janus 库会维护以支持 Python 的最新版本和修复错误,但不会进行重大更改。如果您的应用程序对性能敏感,或者需要 anyio 等新功能支持,可以尝试实验性的 culsans 库作为替代。

交流渠道

GitHub 讨论:https://github.com/aio-libs/janus/discussions

在此自由提问和分享您的想法。

gitter 聊天 https://gitter.im/aio-libs/Lobby

许可

janus 库遵循 Apache 2 许可。

致谢

库的开发得到 DataRobot(https://datarobot.com)的赞助。

项目介绍

Thread-safe asyncio-aware queue for Python

定制我的领域