I am new to python, and I created a Python script that employs multithreading to increase a shared counter. I anticipated that the final value of the counter would reach 1,000,000, as I am executing 10 threads, each adding to the counter 100,000 times. Nevertheless, the outcome consistently falls short of 1,000,000.
Here’s the code I used:
import threading
counter = 0
def increment_counter():
global counter
for _ in range(100000):
counter += 1
threads = []
for _ in range(10):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("Final counter value:", counter)
>Solution :
The problem is from a race condition due to the absence of synchronization when multiple threads attempt to modify the counter at the same time. To resolve this issue, implement a threading.Lock to ensure that only one thread can increase the counter simultaneously:
import threading
counter = 0
lock = threading.Lock()
def increment_counter():
global counter
for _ in range(100000):
with lock:
counter += 1
threads = []
for _ in range(10):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("Final counter value:", counter)