Skip to content

Instantly share code, notes, and snippets.

@tsaylor
Last active August 29, 2015 14:12
Show Gist options
  • Save tsaylor/a4d5beecab41d5f84fe8 to your computer and use it in GitHub Desktop.
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.
import threading
import time
(i, seconds) = (0, 5)
def countdown():
global seconds, i
while i < seconds:
time.sleep(1)
i = i + 1
print
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