Skip to content

Instantly share code, notes, and snippets.

@Olamidun
Created September 27, 2023 21:16
Show Gist options
  • Save Olamidun/817f5c59461a9236a394af8c73484bc9 to your computer and use it in GitHub Desktop.
Save Olamidun/817f5c59461a9236a394af8c73484bc9 to your computer and use it in GitHub Desktop.
Threads with lock
from time import sleep
from threading import Thread, Lock
counter = 10000
lock = Lock() # Instantiate Python thread lock
def decrease_with_thread_locking(by):
global counter
# use the lock instance as a context manager
with lock:
print(f"Initial Balance: {counter}")
local_counter = counter
local_counter -= by
sleep(1)
counter = local_counter
print(f"Updated balance: {counter}")
thread_1 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_2 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_3 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_4 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_5 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_6 = Thread(target=decrease_with_thread_locking, args=(500,))
thread_7 = Thread(target=decrease_with_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()
# P.S: Locking can affect performance a little bit as each process trying to work on the same balance need to wait for one process to release the lock before they can acquire it and subsequently complete execution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment