Nxt-python-threads

From Earlham CS Department
Revision as of 23:58, 24 February 2010 by Brad (talk | contribs) (Basics of threads in Python: - Start)
Jump to navigation Jump to search

Back to Robotics Main Page


Thread Basics

  • Computing device - CPU, RAM, persistant store (two ARM CPUs, etc. in the NXT)
  • Stored program; Fetch, decode, execute
  • Execution context - instructions, data, program counter, stack
    • Processes have all 4 (instructions, data, program counter, stack)
    • Threads have PC and stack with shared ins and data
  • Workshop analogy
  • Concurrency and locking
  • Issues and how they can be addressed
    • Race conditions
    • Deadlock

Basics of threads in Python

Modules

  • thread - low level thread library
  • threading - higher level library built on thread (addressed on this page)

Thread Objects

When creating a thread, you will must always define a class function called run(). This is the code that will be executed by the thread. When the run() function exits, the thread is no longer alive.

import threading

class hello_world_thread( threading.Thread ):
  def run( self ):
    print "Hello World!"

Starting the above thread is done by calling the start() function. This will execute the run() function you've defined.

>>> hw = hello_world_thread() # initialize
>>> hw.start()                # run
Hello World!

If you want to pass arguments to the thread at initialization, define the constructor function: __init__().

class hello_world_thread( threading.Thread ):
  def __init__( self, message="Hello World" ): # default value for message
    threading.Thread.__init__( self ) # init the thread
    self.message = message
  def run( self ):
    print self.message
>>> hello_world_thread().start() # initialize and run
Hello World!
>>> hello_world_thread('Hola Mundo!").start() # init and run with argument
Hola Mundo! 


Lock Objects Condition Objects Semaphore Objects Event Objects Timer Objects