Skip to content

Instantly share code, notes, and snippets.

@Olamidun
Created September 27, 2023 21:08
Show Gist options
  • Save Olamidun/2486fc3f6788ee89709a45a52b0fa353 to your computer and use it in GitHub Desktop.
Save Olamidun/2486fc3f6788ee89709a45a52b0fa353 to your computer and use it in GitHub Desktop.
Race condition without thread locking
from time import sleep
import threading
counter = 10000 # dummy farmer balance in wallet
def decrease_without_thread_locking(by):
global counter
print(f"Initial Balance: {counter}")
local_counter = counter
local_counter -= by # simulate deducting the amount the farmer want to withdraw from the wallet
sleep(1) # sleeping to simulate when it is saving the new balance to the db or performing another task like sending sms to the farmer
counter = local_counter
print(f"Updated balance: {counter}")
# opening multiple threads here to simulate multiple processes trying to acquire the same balance at the same time
thread_1 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_2 = threading.Thread(target=decrease_without_thread_locking, args=(500, ))
thread_3 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_4 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_5 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_6 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_7 = threading.Thread(target=decrease_without_thread_locking, args=(500,))
thread_1.start()
thread_2.start()
thread_3.start()
thread_4.start()
thread_5.start()
thread_6.start()
thread_7.start()
thread_1.join()
thread_2.join()
thread_3.join()
thread_4.join()
thread_5.join()
thread_6.join()
thread_7.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment