Thread pool with a shared deadline
Implement `run_with_timeout(tasks, workers, timeout)` — running a batch of tasks
in a thread pool under one shared deadline.
`tasks` is an iterable of zero-argument callables; `workers` is how many tasks
run at the same time; `timeout` is how many seconds to wait for **all** tasks,
`None` means no limit.
Rules:
- `workers` is an integer `>= 1`, otherwise `ValueError`; `bool` is not a
number;
- `timeout` is a number `> 0` or `None`, otherwise `ValueError`;
- an empty task list returns an empty result list;
- no more than `workers` tasks run at the same time;
- the result list follows the input order, not the completion order;
- if a task raises, the exception of the task with the **smallest index** is
re-raised after the pool finishes; no partial result is returned;
- if not all tasks finish within `timeout` — `TimeoutError`: no new tasks start
and waiting stops;
- worker threads are daemons: a stuck task must not keep the process alive;
- when every task finishes in time, no worker thread is left running.
Example: `run_with_timeout([lambda: 1, lambda: 2], workers=2, timeout=1)`
returns `[1, 2]`; if one task waits on an `Event` nobody sets, the call ends
with `TimeoutError` after `timeout` instead of hanging.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
How does the calling thread learn that **all** tasks are done without polling a
counter in a loop? And what should happen to tasks that have not started when
the deadline expires?