Threading for a newbie

Koncept user at unknown.invalid
Thu Jan 5 17:15:20 EST 2006


Hi. I am fairly new to Python programming and am having some trouble
wrapping my head around threading.

This is a very basic example of what I am trying to do, and would
greatly appreciate having this code hacked to pieces so that I can
learn from you folks with experience.

What I would like to learn from this example is how to use threads to
call on other classes and append/modify results in a list outside of
scope (basically keep track of variables throught the total threading
process and return them somehow afterwards ). I was thinking about
using some sort of global, but I am not sure what the best approach to
this is.

Thanks kindly for any assistance you may be able to offer.

-- code -- 

import time, random, threading

order = []

class Foo:
   def __init__(self, person):
      print "\nFoo() recieved %s\n" % person

class Bar(threading.Thread, Foo):
   def __init__(self, name):
      threading.Thread.__init__(self, name = name)
      self.curName = name
   def run(self):
      global order
      sleepTime = random.randrange(1,6)
      print "Starting thread for %s in %d seconds" % \
         (self.getName(), sleepTime)
      time.sleep(sleepTime)
      Foo.__init__(self,self.getName())
      print "%s's thread has completed" % self.getName()
      order.append(self.getName())

def main():
   for person in ['Bill','Jane','Steve','Sally','Kim']:
      thread = Bar(person)
      thread.start()

   # How do I print "order" after all the threads are complete?
   print "\nThreads were processed in the following order:"
   for i, person in enumerate(order): print "%d. %s" % (i+1,person)

if __name__ == "__main__":
   main()

-- 
Koncept << 
"The snake that cannot shed its skin perishes. So do the spirits who are
prevented from changing their opinions; they cease to be a spirit."  -Nietzsche



More information about the Python-list mailing list