Python 异步上下文

标签 python multithreading asynchronous python-asyncio

在线程中,我们有一个叫做“线程上下文”的东西,我们可以在其中保存一些数据(状态)以供在特殊线程中访问。在 asyncio 中,我需要在当前执行路径中保存一些状态,以便所有后续协程都可以访问它。解决办法是什么? 注意:我知道每个协程函数都是为 asyncio 中的执行路径实例化的,但由于某种原因我无法在函数属性中保存状态。 (虽然这个方法os反正不是很好)

最佳答案

从 Python 3.7 开始,您可以使用 contextvars.ContextVar .

在下面的示例中,我声明了 request_id 并在 some_outer_coroutine 中设置了值,然后在 some_inner_coroutine 中访问了它。

import asyncio
import contextvars

# declare context var
request_id = contextvars.ContextVar('Id of request.')


async def some_inner_coroutine():
    # get value
    print('Processed inner coroutine of request: {}'.format(request_id.get()))


async def some_outer_coroutine(req_id):
    # set value
    request_id.set(req_id)

    await some_inner_coroutine()

    # get value
    print('Processed outer coroutine of request: {}'.format(request_id.get()))


async def main():
    tasks = []
    for req_id in range(1, 5):
        tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))

    await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())

输出:

Processed inner coroutine of request: 1
Processed outer coroutine of request: 1
Processed inner coroutine of request: 2
Processed outer coroutine of request: 2
Processed inner coroutine of request: 3
Processed outer coroutine of request: 3
Processed inner coroutine of request: 4
Processed outer coroutine of request: 4

关于Python 异步上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30596484/

相关文章:

javascript - 我应该如何在 JavaScript 中一个接一个地执行函数?

c# - 在 C# 中的单个调用中进行多个异步调用

c++ - 如何在 SWIG 中使用 C++ 优化标志?

python - Matplotlib:Web 服务器上的交互式绘图

python - 如何将 numpy 数据预加载到像 io.BytesIO 这样的缓冲区中以使其可搜索?

c# - 避免因锁定 WPF 而导致 UI 阻塞

java - JVM(Hotspot)中的 `monitor`是什么,一个特定的对象?

c++ - c++11的线程,用new创建

java - 在 Android 中访问字符串数组中的最后一个 "number"元素

Python 检索 RUID?