Bounded parallelism with a semaphore
Implement `map_limited(func, items, limit)` — a parallel `map` with a hard cap on
the number of concurrent calls.
Rules:
- `limit` is an integer `>= 1`, otherwise `ValueError`; `bool` is not a number;
- each item is processed exactly once;
- no more than `limit` calls to `func` run at the same time;
- results come back in input order, not in completion order;
- an empty list gives an empty result;
- when `limit` exceeds the number of items, extra workers are not needed;
- if `func` raises, new items are not started, the ones already running finish,
and the exception with the **smallest index** propagates;
- after an error no partial results are returned.
Implementation hint: a queue of indices under a shared `Lock`, a pool of
`min(limit, len(items))` threads and a stop flag. `threading.Semaphore` works
too, but with a pool it is easier to guarantee that no new task starts after an
error.
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 many tasks can run at once if there are more workers than `limit`? How do
you guarantee that without every thread polling a counter?