~/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.
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
- Basics: at most k at once basics easy
- Laundromat washers easy
- Bounded blocking queue medium
- Group atoms into water molecules medium