Python
  Home arrow Python arrow Page 4 - Basic Threading in Python
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Basic Threading in Python
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 90
    2005-04-04

    Table of Contents:
  • Basic Threading in Python
  • Using the Threading Module
  • Pooling Threads
  • More Thread Tricks

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Basic Threading in Python - More Thread Tricks
    (Page 4 of 4 )

    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.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · You can "turn an ordinary function into a thread" using the Thread class: just pass...
       · Thanks for pointing that out to me. :))
       ·  Sir: Would you like to give a "mt" example which is more complicated, more...
       · Sorry for the delay. I should really check comments more often....The...
       · Hi,The example with the threadpool works quite well. Except that I do not manage...
       · Thats a great idea but now that I have done that I cannot see what I type in my...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway