Implement run_limited(tasks, k) -> list:
tasksare zero-argument functions (downloads that each need one ofkconnections, say).- Start one thread per task right away, but let at most
krun at once; the rest wait for a running task to finish. - Return the results in task order (
results[i] = tasks[i]()) once all are done.
run_limited([lambda: 1, lambda: 2, lambda: 3], 2) # [1, 2, 3], never more than 2 running
run_limited([], 3) # []
With 6 tasks of 0.1s each and k = 2, the call takes about 0.3s: never more than 2 at once, but always 2 while 2 are waiting.
1 <= k (it may exceed the task count); up to 50 tasks. Don't sleep or busy-wait.
Show hint
a threading.Semaphore(k) holds k permits: wrap each task in with sem:, and the (k+1)-th thread blocks until someone releases.