Skip to content

Commit fa9fd6d

Browse files
authored
Provide an example of using an in-process queue
1 parent b9b4a72 commit fa9fd6d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

docs/howto/patterns.rst

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,30 @@ terminates, after canceling the other task::
8787
for task in pending:
8888
task.cancel()
8989

90+
In-process queue
91+
----------------
92+
93+
For simple applications that need to be able to consume and act on multiple
94+
messages at one, an in-process queue can be leveraged::
95+
96+
queue = asyncio.Queue()
97+
98+
async def consumer_handler(websocket):
99+
for message in websocket:
100+
queue.put(message)
101+
102+
async def worker():
103+
while True:
104+
message = await queue.get()
105+
result = await long_running_task(message)
106+
await websocket.send(result)
107+
108+
async def handler(websocket):
109+
async with asyncio.TaskGroup() as tg:
110+
tg.create_task(consumer_handler(websocket))
111+
for _ in range(os.cpu_count()):
112+
tg.create_task(worker())
113+
90114
Registration
91115
------------
92116

0 commit comments

Comments
 (0)