asyncio — async/await and the Event Loop — Concept Check
Questions on asyncio — async/await and the Event Loop. asyncio runs thousands of concurrent I/O operations on one thread: coroutines pause at await, the event loop switches to whoever is ready, and gather fans out work — as long as nothing blocks the loop.
Questions in this quiz
8 questions on asyncio — async/await and the Event Loop — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.In an asyncio-based Python web service, a developer uses time.sleep(5) inside an async endpoint. What is the likely impact?
- AOnly the current coroutine will be delayed for 5 seconds.
- BThe entire event loop will be blocked for 5 seconds.
- CThe service will handle other requests during the sleep period.
- DThe sleep call will be ignored in an async context.
2.A developer uses asyncio.gather to call three services with varying response times. What will determine the total execution time?
- AThe average response time of all services.
- BThe response time of the fastest service.
- CThe response time of the slowest service.
- DThe sum of all service response times.
3.What happens if a coroutine calls a blocking function like requests.get without using an async library?
- AThe coroutine will automatically switch to a non-blocking mode.
- BThe coroutine will crash, stopping the event loop.
- CThe coroutine will block the event loop, affecting all tasks.
- DThe coroutine will run asynchronously without issues.
4.A developer uses asyncio.to_thread to handle a legacy blocking function. What is the benefit?
- AIt runs the blocking code in a separate thread, avoiding event loop blockage.
- BIt converts the blocking code into a non-blocking coroutine.
- CIt runs the blocking code asynchronously within the event loop.
- DIt automatically optimizes the blocking code for async execution.
5.What is the primary role of the event loop in asyncio?
- ATo execute blocking functions concurrently.
- BTo handle multi-threaded execution.
- CTo automatically optimize code for performance.
- DTo manage and switch between coroutines.
6.In the provided code, what is the expected output time when using asyncio.gather for three service calls?
- AApproximately 3.7 seconds.
- BApproximately 1.2 seconds.
- CApproximately 2.0 seconds.
- DApproximately 1.5 seconds.
7.A developer mistakenly uses time.sleep instead of asyncio.sleep in an async function. What should they expect?
- AThe function will run asynchronously without issues.
- BThe function will block the event loop, delaying all coroutines.
- CThe function will crash, causing an exception.
- DThe event loop will automatically convert it to asyncio.sleep.
8.Which of the following is a correct use of asyncio.create_task?
- ATo start a coroutine immediately and await it later.
- BTo optimize a coroutine for faster execution.
- CTo run a coroutine in a separate thread for better performance.
- DTo convert a blocking function into a coroutine.