[Tutor] Timed While Loops and Threads

Michael H. Goldwasser goldwamh at slu.edu
Sun Dec 9 05:11:02 CET 2007

Hi everyone,

I'm having some fun combining two recent topics: the "Timed While
Loops" game and that of communication between threads.  Here is an
example that allows a person to gather points in a while loop, but
only for a fixed period of time.  It relies on a few shared variables
to coordinate the activity of the main thread and the secondary

import threading

def playGame():
    global score, inPlay     # shared with main thread
    while inPlay:
        raw_input('Press return to score a point! ')
        if inPlay:
            score += 1
            print 'Score =', score

score = 0
inPlay = True
numSeconds = 5       # I didn't have patience for the 30 second version
T = threading.Thread(target=playGame)
inPlay = False       # signal to secondary thread that game is over
print 'After', numSeconds, 'seconds, you scored', score, 'points.'

       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007

More information about the Tutor mailing list