跳至内容

Asyncio

python asyncio 如何获取当前的协程 id 编号 - SegmentFault 思否

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import asyncio
import contextvars
# 申明Context变量
request_id = contextvars.ContextVar('Id of request')

async def main():
	# 设置并发数
	max_concurrent = 5
	semaphore = asyncio.Semaphore(max_concurrent)

	# 内部函数,不显式传参
	async def get():
		# Get Value
		print(f'Request ID (Inner): {request_id.get()}')

	# 协程
	async def limited_task_lq(task_id: int):
		async with semaphore:
			request_id.set(task_id)
			await get()
			print(f'Request ID (Outer): {request_id.get()}')

	await asyncio.gather(
		*[limited_task_lq(task_id=i % max_concurrent) for i in range(15)])
if __name__ == "__main__":
	asyncio.run(main())
最后更新于