Created
September 27, 2023 21:08
-
-
Save Olamidun/2486fc3f6788ee89709a45a52b0fa353 to your computer and use it in GitHub Desktop.
Race condition without thread locking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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