Implement Concurrent Any-True Shot
TemporalSoftware Engineer · Technical ScreenLast updated
This question tests the ability to manage concurrent asynchronous tasks, specifically implementing logic to return the first 'True' result while efficiently cancelling remaining pending tasks.
Problem Statement
Implement a function any_true(tasks) that takes a list of asynchronous functions (each returning a boolean) and returns True as soon as the first function returns True. If all functions return False, the method should return False. If any function raises an exception, it should be treated as a False result unless no other tasks are running.
Crucially, once a True result is observed, your implementation must attempt to cancel all other pending tasks to save resources.
You may use standard library primitives (e.g., asyncio in Python). Assume the input tasks is a list of awaitable objects.
Function Signature
async def any_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool:
pass
Example
- Input:
[task_a, task_b, task_c]wheretask_atakes 5s,task_btakes 1s, andtask_ctakes 10s. - Output:
True(after 1s, assumingtask_breturnsTrue). - Requirement:
task_aandtask_cshould be cancelled immediately upontask_breturningTrue.
Constraints
- The number of tasks can range from 0 to 1000.
- Each task is an independent async function.
- Handle potential race conditions where multiple tasks return
Truesimultaneously.
Hints
Hint 1
Use `asyncio.create_task` to schedule all functions to run concurrently.
Hint 2
Consider using `asyncio.wait` with `FIRST_COMPLETED` to monitor the progress of the tasks.
Hint 3
Maintain a set of task references so that once a `True` is found, you can iterate through the set and call `cancel()` on all remaining tasks.
Follow-up questions
- How would your implementation change if we needed to return the index of the task that first returned True?
- What are the implications of task cancellation not being instantaneous in the underlying runtime?
- How would you implement a timeout mechanism to ensure the entire operation doesn't hang indefinitely?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.