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?