Loading…
Loading…
N_THREADS threads each need to run a "process" step, but only PERMITS of them may run that step at the same time (e.g. it hits a rate-limited resource). Print how many threads successfully completed processing.
Why this is gradable. Concurrent code can legitimately produce different interleavings on every run, so this practice bank only includes problems whose correctness reduces to one deterministic final value or invariant — never a specific thread ordering. If your solution is correct, it will print the exact same output on every run, no matter how the scheduler interleaves your threads. Every thread eventually acquires a permit, runs, and releases it — so the final processed count is always
N_THREADS, regardless of scheduling. What the semaphore actually buys you (bounding concurrent access to a limited resource) isn't visible in the final count — it's a live property, which is exactly why real systems monitor it separately with metrics, not a post-hoc output diff. This problem checks the shape of the pattern: using a semaphore correctly should never lose or double-count work.
Input: N_THREADS = 20, PERMITS = 3
Output: 20
A threading.Semaphore(permits) lets up to permits threads through at once; any additional thread blocks until one of the others releases. Wrap the "process" step in with sem: (or explicit acquire/release), and record completion under a separate lock so the counter itself doesn't race.
Line 1: two space-separated integers, N_THREADS and PERMITS
Print the number of threads that completed processing.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.