DEV Community

Hitesh
Hitesh

Posted on

Race Condition in Python.

A race condition happens when two or more threads or processes try to access and modify the same shared resource at the same time, and the program's behavior depends on the timing of their execution.

Key Points:

  1. Cause: Occurs due to a lack of proper synchronization.
  2. Effect: Leads to unpredictable or incorrect outcomes because the threads "race" to complete their operations first.
  3. Example:

    • Two threads try to update a shared counter:
     counter = 0
    
     def increment():
         global counter
         for _ in range(1000):
             counter += 1  # This is not thread-safe
    
     thread1 = threading.Thread(target=increment)
     thread2 = threading.Thread(target=increment)
    
     thread1.start()
     thread2.start()
     thread1.join()
     thread2.join()
    
     print(counter)  # Output may vary and be less than 2000
    
  • Without proper synchronization, the result is unpredictable because threads interfere with each other.

How to Prevent:

  • Use locks (e.g., Lock or RLock) to ensure only one thread accesses the critical section at a time.
  • Example with a lock:
  import threading

  counter = 0
  lock = threading.Lock()

  def increment():
      global counter
      for _ in range(1000):
          with lock:  # Ensures only one thread accesses this block at a time
              counter += 1

  thread1 = threading.Thread(target=increment)
  thread2 = threading.Thread(target=increment)

  thread1.start()
  thread2.start()
  thread1.join()
  thread2.join()

  print(counter)  # Output will always be 2000
Enter fullscreen mode Exit fullscreen mode

Interview Tips:

  • Tt’s caused by unsynchronized access to shared resources.
  • Always mention locks or synchronization to prevent it.

Top comments (0)