Skip to content

Instantly share code, notes, and snippets.

@MBlore
Created April 19, 2023 20:12
Show Gist options
  • Save MBlore/4d38394ac25a0c1cc6c2d1c82eb67cc9 to your computer and use it in GitHub Desktop.
Save MBlore/4d38394ac25a0c1cc6c2d1c82eb67cc9 to your computer and use it in GitHub Desktop.
import threading
import time
items = []
lock = threading.Lock() # Shared lock object for our threads.
# Thread work function.
def do_work():
thread_id = threading.get_ident()
"""
if lock.locked():
print(f"Thread {thread_id}: Someone has the lock, no need for me to check the pizza item.")
return
"""
print(f"Thread {thread_id} is trying to acquire the lock...")
print(f"Thread {thread_id} now has the lock.")
if "Pizza" not in items:
lock.acquire() # 1000 threads waiting...
if "Pizza" not in items:
print(f"Thread {thread_id} is going to add the 'Pizza'.")
time.sleep(10)
items.append("Pizza")
else:
print(f"Thread {thread_id} is NOT going to add the 'Pizza'.")
lock.release()
print(f"Thread {thread_id} has now released the lock.")
# Spawn 10 threads.
threads = []
for i in range(100):
thread = threading.Thread(target=do_work)
thread.start()
threads.append(thread)
# Wait for all threads to finish.
for t in threads:
t.join() # Wait for this thread to finish.
print("All threads have finished, lets see whats in the list.")
print("------------------------------------------------------")
# Lets see whats in the list.
print(items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment