~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Semaphore
Counting access to N resources; producer/consumer.
Main path: 4 problems, about 65 min.
Notes
Recognise it when: counting resources, such as N free slots, N connections, or "at most K at once".
free = threading.Semaphore(capacity) # slots
items = threading.Semaphore(0) # things to consume
mutex = threading.Lock()
# producer # consumer
free.acquire() items.acquire()
with mutex: q.append(x) with mutex: x = q.popleft()
items.release() free.release()
Gotchas
- Unlike a Lock, any thread can
release(). That's what makes hand-offs work. - Order matters: acquire the semaphore before the mutex, or you deadlock.
4 problems
Concurrency
Coordination Semaphores, conditions and barriers.
Semaphore guide
- At most k at once basics py · c++ · java easy
- Laundromat washers py · c++ · java easy
- Bounded blocking queue py · c++ · java medium
- Group atoms into water molecules py · c++ · java medium