progress

~/problems / Coordination / Semaphore

At most k at once

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Implement run_limited(tasks, k) -> list:

  • tasks are zero-argument functions (downloads that each need one of k connections, say).
  • Start one thread per task right away, but let at most k run 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.

Topic: Semaphore. Counting access to N resources; producer/consumer.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc