python3.7 contextvars在asyncio使用的

from contextvars import ContextVar

import asyncio
import random

cv = ContextVar('cv')


async def waiting_func(name):
    print(f'{name} Before sleep: {cv.get()}')
    await asyncio.sleep(random.random())
    print(f'{name} After 1 sleep: {cv.get()}')
    await asyncio.sleep(random.random())
    print(f'{name} After 2 sleep: {cv.get()}')


async def task(name):
    await waiting_func(name)


async def main():
    for name in ('first', 'second', 'third'):
        cvt = cv.set(name)
        await task(name)
        cv.reset(cvt)


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

转载于:https://www.cnblogs.com/c-x-a/p/10342116.html

你可能感兴趣的:(python3.7 contextvars在asyncio使用的)