I tried out the code found here and found some unexpected behavior. I reproduce the code below
import threading
shared_balance = 0
N = 500
class Deposit(threading.Thread):
def run(self):
for _ in range(N):
global shared_balance
shared_balance += 1
class Withdraw(threading.Thread):
def run(self):
for _ in range(N):
global shared_balance
shared_balance -= 1
threads = [Deposit(), Withdraw()]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(shared_balance)
When I try to run this for N = 500
, I always see 0 - that means no statements are executed out of order. However, when I set N = 500000
, I always see a non zero result - proving that the statements are executed out of order.
Is there an explanation for why this happens? The time taken by shared_balance += 1
should always be the same - so I'm not sure why increasing the N
causes python to switch the running thread.
Thanks!