Sobes.tech
Middle

Analyze the following Python code that uses threading to increment a counter variable: ```python import threading import time counter = 0 def increment(): global counter for _ in range(100000): current = counter counter = current + 1 thread1 = threading.Thread(target=increment) thread2 = threading.Thread(target=increment) thread1.start() thread2.start() thread1.join() thread2.join() print(f"Итоговое значение счетчика: {counter}") ``` Explain what the expected output is and discuss any potential issues with this code when using threads.

sobes.tech AI

Answer from AI

Expected result is a counter value around 200,000, since two threads each perform 100,000 increments.

However, due to the lack of synchronization between threads, a race condition occurs. The operation counter = current + 1 is not atomic: a thread reads the value, increments it, and writes it back. If both threads read the same value simultaneously, one increment will be lost.

As a result, the final counter value will be less than 200,000 and will vary across different runs.

To fix this, a lock (e.g., threading.Lock) should be used to protect the critical section:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

This ensures that only one thread modifies counter at a time, and the final result will be correct.