|
| 1 | +import asyncio |
| 2 | +import random |
| 3 | +import time |
| 4 | + |
| 5 | + |
| 6 | +async def main(): |
| 7 | + queue = asyncio.Queue() |
| 8 | + user_ids = [1, 2, 3] |
| 9 | + |
| 10 | + start = time.perf_counter() |
| 11 | + await asyncio.gather( |
| 12 | + producer(queue, user_ids), |
| 13 | + *(consumer(queue) for _ in user_ids), |
| 14 | + ) |
| 15 | + end = time.perf_counter() |
| 16 | + print(f"\n==> Total time: {end - start:.2f} seconds") |
| 17 | + |
| 18 | + |
| 19 | +async def producer(queue, user_ids): |
| 20 | + async def fetch_user(user_id): |
| 21 | + delay = random.uniform(0.5, 2.0) |
| 22 | + print(f"Producer: fetching user by {user_id=}...") |
| 23 | + await asyncio.sleep(delay) |
| 24 | + user = {"id": user_id, "name": f"User{user_id}"} |
| 25 | + print(f"Producer: fetched user with {user_id=} (done in {delay:.1f}s)") |
| 26 | + await queue.put(user) |
| 27 | + |
| 28 | + await asyncio.gather(*(fetch_user(uid) for uid in user_ids)) |
| 29 | + for _ in range(len(user_ids)): |
| 30 | + await queue.put(None) # Sentinels for consumers to terminate |
| 31 | + |
| 32 | + |
| 33 | +async def consumer(queue): |
| 34 | + while True: |
| 35 | + user = await queue.get() |
| 36 | + if user is None: |
| 37 | + break |
| 38 | + delay = random.uniform(0.5, 2.0) |
| 39 | + print(f"Consumer: retrieving posts for {user['name']}...") |
| 40 | + await asyncio.sleep(delay) |
| 41 | + posts = [f"Post {i} by {user['name']}" for i in range(1, 3)] |
| 42 | + print( |
| 43 | + f"Consumer: got {len(posts)} posts by {user['name']}" |
| 44 | + f" (done in {delay:.1f}s):" |
| 45 | + ) |
| 46 | + for post in posts: |
| 47 | + print(f" - {post}") |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + random.seed(444) |
| 52 | + asyncio.run(main()) |
0 commit comments