Concurrency Patterns
1. Producer-Consumer Pattern
Using Python Condition
Conditionimport threading
class BoundedBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = []
self.condition = threading.Condition()
def produce(self, item):
with self.condition:
while len(self.buffer) == self.capacity:
self.condition.wait() # Wait until buffer is not full
self.buffer.append(item)
self.condition.notify() # Notify consumer
def consume(self):
with self.condition:
while len(self.buffer) == 0:
self.condition.wait() # Wait until buffer is not empty
item = self.buffer.pop(0)
self.condition.notify() # Notify producer
return item2. Print FooBar Alternately
Using Python Event (or Semaphore)
Event (or Semaphore)3. Reader-Writer Lock
Concepts Checklist for SDE 3
Interview Strategy
Quick Revision
Last updated