Home arrow Python arrow Page 4 - Basic Threading in Python

More Thread Tricks - Python

If you want your application to perform several tasks at once, you can use threads. Python can handle threads, but many developers find thread programming to be very tricky. Among other points, Peyton McCullough covers how to spawn and kill threads in this popular language.

TABLE OF CONTENTS:
  1. Basic Threading in Python
  2. Using the Threading Module
  3. Pooling Threads
  4. More Thread Tricks
By: Peyton McCullough
Rating: starstarstarstarstar / 157
April 04, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

There is more to threads than just spawning them and sending them on their way. The threading module's Thread module contains a few more methods that you should be aware of. The first two deal with naming threads. The method setName sets a thread's name, and the method getName retrieves a thread's name:

import threading

class TestThread ( threading.Thread ):

   def run ( self ):

      print 'Hello, my name is', self.getName()

cazaril = TestThread()
cazaril.setName ( 'Cazaril' )
cazaril.start()

ista = TestThread()
ista.setName ( 'Ista' )
ista.start()

TestThread().start()

No suprises there. Also, as you can see, threads have names even if you don't specify them.

We can also check whether a thread is “alive” using the isAlive method. If the thread hasn't finished executing whatever is in its run method, then it's classified as being alive:

import threading
import time

class TestThread ( threading.Thread ):

   def run ( self ):

      print 'Patient: Doctor, am I going to die?'

class AnotherThread ( TestThread ):

   def run ( self ):

      TestThread.run( self )
      time.sleep ( 10 )

dying = TestThread()
dying.start()
if dying.isAlive():
   print 'Doctor: No.'
else:
   print 'Doctor: Next!'

living = AnotherThread()
living.start()
if living.isAlive():
   print 'Doctor: No.'
else:
   print 'Doctor: Next!'

The second thread remains alive because we force it to wait using the time module's sleep method.

If we want to make a thread wait for another thread to terminate itself, we can use the join method:

import threading
import time

class ThreadOne ( threading.Thread ):

   def run ( self ):

      print 'Thread', self.getName(), 'started.'
      time.sleep ( 5 )
      print 'Thread', self.getName(), 'ended.'

class ThreadTwo ( threading.Thread ):

   def run ( self ):

      print 'Thread', self.getName(), 'started.'
      thingOne.join()
      print 'Thread', self.getName(), 'ended.'

thingOne = ThreadOne()
thingOne.start()
thingTwo = ThreadTwo()
thingTwo.start()

We can use the setDaemon method, too. If a True value is passed with this method and all other threads have finished executing, the Python program will exit, leaving the thread by itself:

import threading
import time

class DaemonThread ( threading.Thread ):

   def run ( self ):

      self.setDaemon ( True )
      time.sleep ( 10 )

DaemonThread().start()
print 'Leaving.'

Python also contains a thread module that deals with lower level threading. The only feature I would like to point out is the start_new_thread function it contains. Using this, we can turn an ordinary function into a thread:

import thread

def thread( stuff ):
   print "I'm a real boy!"
   print stuff

thread.start_new_thread ( thread, ( 'Argument' ) )

Conclusion

There's much more to multi-threading than I explained in this article, but I will not bore you by extending the scope of this article to include everything. Moreover, as Guido van Rossum mentioned, the advantage gained by complex multi-threading in Python may be outweighed by the consequences. A small dose of common sense can eliminate much of the problems in simple multi-threading, however.

Threading is very important when dealing with computer applications, and, as I mentioned earlier, Python isn't excluded. When used properly, threads can be very beneficial and often even crucial, as I've outlined in this article.



 
 
>>> More Python Articles          >>> More By Peyton McCullough
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: