[CentralOH] Python threads

Bryan Harris harrisbw at notes.udayton.edu
Mon Aug 4 19:34:58 CEST 2008


Hi all,
Does anybody have any experience with threads in Python.  I wanted to
play with threads in python so I pulled down this code which looked
like a good starting place.  (First or second page of Google.)

It is obviously supposed to spawn 20 threads that then sleep for a
random time.  The proof would be that they report back out of order.
What really happens is that the threads report back in order with
random waits in between.  Obviously sleep isn't releasing the current
thread.

Is there some way to tell if you have threading support in the
interpreter you're running?  I read the "threading" module will import
dummy_threads if you don't have threading support.  How can you tell?

import threading
import time
import random

theVar = 1

class MyThread ( threading.Thread ):

   def run ( self ):

      global theVar
      time.sleep(random.random()*10)
      print 'This is thread ' + str ( theVar ) + ' speaking.'
      print 'Hello and good bye.'
      theVar = theVar + 1

for x in xrange ( 20 ):
    MyThread().start()

-- 
Bryan Harris
Research Engineer
Structures and Materials Evaluation Group
harrisbw at notes.udayton.edu
http://www.udri.udayton.edu/
(937) 229-5561


More information about the CentralOH mailing list