Skip to content

Instantly share code, notes, and snippets.

@BenHamm
Last active March 24, 2019 22:27
Show Gist options
  • Save BenHamm/f87df7ed7aaf95e2a62a5860cdd0ae3d to your computer and use it in GitHub Desktop.
Save BenHamm/f87df7ed7aaf95e2a62a5860cdd0ae3d to your computer and use it in GitHub Desktop.
Threading condition vars
import threading
import time
condition = threading.Condition()
def lock_door():
global condition
while True:
print("Lock Thread: Door lock armed")
condition.acquire()
condition.wait()
print("Lock Thread: Woke up")
condition.release()
print("Lock Thread: Got prey signal. Locking door...")
time.sleep(7)
print("Lock Thread: Lockout Period Reached. Unlocking door.")
time.sleep(7)
# start consumer
c = threading.Thread(name='c', target=lock_door)
c.start()
time.sleep(2) #a short nap to avoid race condition
print 'Main Thread: Sending first unlock signal (should succeed)'
condition.acquire()
condition.notifyAll()
condition.release()
time.sleep(2)
print 'Main Thread: Sending second unlock signal (should fail)'
condition.acquire()
condition.notifyAll()
condition.release()
time.sleep(15)
print 'Main Thread: Sending third unlock signal (should succeed)'
condition.acquire()
condition.notifyAll()
condition.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment