Limit Concurrent Work with a Typed Semaphore
Write the code, see it run, pass the checks.
The problem
- hard
- Code
Write a class Semaphore, constructed with a limit. acquire() resolves once fewer than limit holders are in, release() gives the slot to the longest-waiting caller (or frees it), and use(fn) acquires, runs the async fn, always releases, even when fn fails, and resolves or rejects with fn's result. Type it so the limit must be a number, acquire resolves with nothing and use resolves to fn's resolved type.
Your code must pass
- Lets at most limit holders in at once
- Hands out slots in the order asked
- use releases even when fn fails
- Has no type errors
- use resolves with fn's type
- acquire resolves with nothing
- Takes a numeric limit