Editor

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 lesson

Create a SafeCounter class with:

  • An __init__ that sets self.value = 0 and creates a threading.Lock()
  • An increment() method that uses the lock to safely add 1 to value
  • A get() method that returns the current value
  • Create 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

    All Python exercises · 50 practice problems · Advanced Python quiz