Fix the Bug: Missing Lock
Advanced · Fix the bug · from Python Threading vs Multiprocessing vs asyncio: When to Use What
From the lesson: Python Threading vs Multiprocessing vs asyncio: When to Use What
Most programs you've written so far do one thing at a time. But real applications need to handle multiple tasks: downloading files while updating a progress bar, serving web requests from many users, or crunching numbers across all CPU cores.
Read the lessonThis SharedList class is meant to be thread-safe, but the add() method doesn't use the lock. Fix the code so that add() and get_all() both use the lock properly.
After the fix, add three items and print the list.
import threading
class SharedList:
def __init__(self):
self.items = []
self.lock = threading.Lock()
def add(self, item):
# Bug: no lock protection!
self.items.append(item)
def get_all(self):
with self.lock:
return list(self.items)
shared = SharedList()
shared.add('alpha')
shared.add('beta')
shared.add('gamma')
print(shared.get_all())
More Concurrency exercises
- Concurrency Decision MakerAdvanced
- Build a Thread-Safe CounterAdvanced
- Predict the Output: asyncio.gatherAdvanced
- Build a Task QueueAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz