Last active
August 13, 2017 03:13
-
-
Save schedutron/4f98565c5bbe015eed10d2d9f5ad7fe0 to your computer and use it in GitHub Desktop.
A demo script for threading.Event synchronization primitive
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 random, time | |
from threading import Event, Thread | |
event = Event() | |
def waiter(event, nloops): | |
for i in range(nloops): | |
print(“%s. Waiting for the flag to be set.” % (i+1)) | |
event.wait() # Blocks until the flag becomes true. | |
print(“Wait complete at:”, time.ctime()) | |
event.clear() # Resets the flag. | |
print() | |
def setter(event, nloops): | |
for i in range(nloops): | |
time.sleep(random.randrange(2, 5)) # Sleeps for some time. | |
event.set() | |
threads = [] | |
nloops = random.randrange(3, 6) | |
threads.append(Thread(target=waiter, args=(event, nloops))) | |
threads[-1].start() | |
threads.append(Thread(target=setter, args=(event, nloops))) | |
threads[-1].start() | |
for thread in threads: | |
thread.join() | |
print(“All done.”) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment