Example of Threading using the threading module

a1eio 0 Tallied Votes 392 Views Share

For more information on threading read this excellent 4 page tutorial:

# counterTest.py, a1eio

import threading

# create a thread object that will do the counting in a separate thread
class Counter(threading.Thread):
    def __init__(self, value, increment):
        threading.Thread.__init__(self) # init the thread
        self.value = value # initial value
        self.increment = increment # amount to increment
        self.alive = False # controls the while loop in the run command

    def run(self): # this is the main function that will run in a separate thread
        self.alive = True
        while self.alive:
            self.value += self.increment # do the counting

    def peek(self): # return the current value
        return self.value

    def finish(self): # close the thread, return final value
        self.alive = False # stop the while loop in 'run'
        return self.value # return value

def main():
    # create separate instances of the counter
    counterA = Counter(1, 1) #initial value, increment
    counterB = Counter(1, 2) #initial value, increment
    counterC = Counter(1, 3) #initial value, increment

    # start each counter

    print "Enter A, B, or C to view counters\nEnter Q to quit"
    while True:
        Input = raw_input("> ").upper() # get input

        if Input == 'A':
            print 'CounterA: ', counterA.peek() # print counterA's value
        elif Input == 'B':
            print 'CounterB: ', counterB.peek() # print counterB's value
        elif Input == 'C':
            print 'CounterC: ', counterC.peek() # print counterC's value
        elif Input == 'Q': # if user entered q or Q, program quits
            # call the function that finishes each counter and print the returned value
            print 'CounterA: ', counterA.finish()
            print 'CounterB: ', counterB.finish()
            print 'CounterC: ', counterC.finish()
            return # exit the Main function


if __name__ == '__main__':