作者:拍友2502887597 | 来源:互联网 | 2023-05-16 22:49
fromcontextvarsimportContextVarimportasyncioimportrandomcvContextVar(cv)asyncdef
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())