Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python multithreading bug

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading