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

why there is no race condition using global python variable

I have the following code:

from threading import Thread, Lock

value = 0

def adder(amount, repeats):
    global value
    for _ in range(repeats):
        value += amount
 
def subtractor(amount, repeats):
    global value
    for _ in range(repeats):
        value -= amount

def main():
    value = 0

    adder_thread = Thread(target=adder, args=(100, 1000000))
    subtractor_thread = Thread(target=subtractor, args=(100, 1000000))

    subtractor_thread.start()
    adder_thread.start()

    print('Waiting for threads to finish...')

    adder_thread.join()
    subtractor_thread.join()

    print(f'Value: {value}')

if __name__ == '__main__':
    main()

What I don’t understand is why I do not have a race condition here? We have global variable, two threads, it suppose to give different values when subtracting and adding, but for me it’s always giving 0. How to make race condition in this example? Is the global variable protected with some synchronisation primitive?

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 :

your code can create race condition.
but the value that you are printing is zero because of this line.

def main():
    value = 0

you declare a value in main which you try to print and it won’t access the global one.
try this:

def main():
    global value
    value = 0
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