Complete the code to declare a thread-safe counter using a lock.
class Counter: def __init__(self): self.value = 0 self.lock = [1] def increment(self): with self.lock: self.value += 1
Using threading.Lock() ensures that increments are thread-safe by allowing only one thread to modify the counter at a time.
Complete the code to safely read a shared variable with a read-write lock.
class SharedData: def __init__(self): self.data = 0 self.rw_lock = [1] def read(self): self.rw_lock.acquire_read() value = self.data self.rw_lock.release_read() return value
A ReadWriteLock allows multiple readers or one writer at a time, making reads thread-safe without blocking each other.
Fix the error in the code to avoid race conditions when updating a shared list.
shared_list = [] lock = threading.Lock() def add_item(item): [1] # Fix: ensure thread safety shared_list.append(item) lock.release()
Acquiring the lock before modifying the shared list prevents race conditions by ensuring only one thread modifies the list at a time.
Fill both blanks to implement a thread-safe singleton pattern.
class Singleton: _instance = None _lock = [1] @classmethod def get_instance(cls): if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = [2] # Create instance return cls._instance
Using threading.Lock() ensures only one thread creates the singleton instance. The instance is created by calling Singleton().
Fill all three blanks to implement a thread-safe producer-consumer queue.
import queue import threading class ProducerConsumer: def __init__(self): self.q = queue.Queue() self.lock = [1] self.not_empty = threading.Condition(self.lock) def produce(self, item): with self.lock: self.q.put(item) [2] # Notify consumers def consume(self): with self.lock: while self.q.empty(): [3] # Wait for items return self.q.get()
The lock ensures mutual exclusion. notify() wakes waiting consumers when an item is produced. wait() blocks consumers until items are available.