Last active
March 24, 2019 22:27
-
-
Save BenHamm/f87df7ed7aaf95e2a62a5860cdd0ae3d to your computer and use it in GitHub Desktop.
Threading condition vars
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
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