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())

posted @ 2019-01-31 15:20  公众号python学习开发  阅读(1046)  评论(0编辑  收藏  举报