Concurrent Async Tasks
Write an asyncio program that "fetches" n items concurrently (each using asyncio.sleep), and report whether the total runtime shows they ran concurrently.
Approach: define an async fetch_item coroutine, run n of them together with asyncio.gather(), time the whole thing, and classify the result the same way as the threading problem — a classification rather than a raw timing value.
Input: One line: the number of items to "fetch", n.
Output: Two lines: "Fetched <n> items", then "Concurrent" if they clearly ran together, or "Sequential" otherwise.
5
Fetched 5 items Concurrent
- 1 <= n <= 10
Hint 1
asyncio.gather(*(fetch_item(i) for i in range(n))) runs all n coroutines concurrently and waits for them all.
Hint 2
await asyncio.sleep(...) (not time.sleep()) is what lets other tasks run during the wait.
Hint 3
Use the same style of threshold check as a threading concurrency check: elapsed < 0.4 * n * 0.7 implies real concurrency.
asyncio.gather() schedules all n fetch_item coroutines on the event loop at once; since each one awaits asyncio.sleep() rather than blocking, the event loop can run all of them concurrently on a single thread. As with the threading problem, comparing elapsed time against a generous threshold (well below the fully-sequential total) classifies the result without depending on an exact, non-reproducible timing value.