Build a Thread-Safe Counter
Advanced · Write the code · 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 lessonCreate a SafeCounter class with:
__init__ that sets self.value = 0 and creates a threading.Lock()increment() method that uses the lock to safely add 1 to valueget() method that returns the current valueCreate a counter, call increment() 100 times in a loop, and print the final value.
import threading
# Create SafeCounter class with lock-based increment
# Create counter, increment 100 times, print result
More Concurrency exercises
- Concurrency Decision MakerAdvanced
- Predict the Output: asyncio.gatherAdvanced
- Fix the Bug: Missing LockAdvanced
- Build a Task QueueAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz