Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you prevent race conditions when using threads in Python? Python में threads use करते समय race conditions को कैसे रोकें?

Answer

A race condition occurs when multiple threads access and modify shared data simultaneously, producing unpredictable results. Locks (threading.Lock) ensure only one thread can access a critical section at a time.

import threading

counter = 0

def increment_unsafe():
    global counter
    for _ in range(100000):
        counter += 1  # NOT atomic - read, add, write can be interrupted mid-operation

threads = [threading.Thread(target=increment_unsafe) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)  # often LESS than 400000 due to race conditions - unpredictable!

# FIX using a Lock
counter_safe = 0
lock = threading.Lock()

def increment_safe():
    global counter_safe
    for _ in range(100000):
        with lock:  # only one thread can be inside this block at a time
            counter_safe += 1

threads = [threading.Thread(target=increment_safe) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter_safe)  # always exactly 400000 - correct and predictable

# Other synchronization primitives:
# - RLock: reentrant lock, same thread can acquire it multiple times
# - Semaphore: allows a limited NUMBER of threads through at once
# - Event: threads wait until a flag is set
# - Condition: threads wait for a specific condition to become true

semaphore = threading.Semaphore(3)  # max 3 threads access a resource concurrently
def limited_access():
    with semaphore:
        print('Accessing limited resource')

Race condition तब होता है जब multiple threads shared data को एक साथ access और modify करते हैं, unpredictable results देते हैं। Locks (threading.Lock) सुनिश्चित करते हैं कि एक समय में सिर्फ एक thread critical section access करे।

import threading

counter = 0

def increment_unsafe():
    global counter
    for _ in range(100000):
        counter += 1  # atomic नहीं है

threads = [threading.Thread(target=increment_unsafe) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)  # अक्सर 400000 से कम - unpredictable!

# Lock से FIX
counter_safe = 0
lock = threading.Lock()

def increment_safe():
    global counter_safe
    for _ in range(100000):
        with lock:
            counter_safe += 1

threads = [threading.Thread(target=increment_safe) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter_safe)  # हमेशा 400000 - सही

# अन्य synchronization primitives:
# - RLock, Semaphore, Event, Condition

semaphore = threading.Semaphore(3)
def limited_access():
    with semaphore:
        print('सीमित resource access हो रहा है')

Was this answer clear?