Last active
August 29, 2015 14:12
-
-
Save tsaylor/a4d5beecab41d5f84fe8 to your computer and use it in GitHub Desktop.
An example of threaded python code. Starts with a number of seconds entered by the user, then spawns a thread to countdown those seconds and another to prompt the user to add more seconds to the clock. Demonstrates one thread manipulating another.
This file contains 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 | |
(i, seconds) = (0, 5) | |
def countdown(): | |
global seconds, i | |
while i < seconds: | |
time.sleep(1) | |
i = i + 1 | |
print "boom!" | |
def menu(): | |
global seconds, i | |
entry = raw_input("seconds to add: ") | |
while entry != "quit": | |
if entry == 'sec': | |
print seconds | |
elif entry == 'sec left': | |
print seconds - i | |
else: | |
try: | |
seconds = seconds + int(entry) | |
except ValueError: | |
pass | |
entry = raw_input("seconds to add: ") | |
c = threading.Thread(target=countdown) | |
c.start() | |
m = threading.Thread(target=menu) | |
m.daemon = True | |
m.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment