NewBie Doubt in Python Thread Programming

Chris Angelico rosuav at gmail.com
Wed May 11 03:15:25 EDT 2011


On Wed, May 11, 2011 at 4:57 PM, vijay swaminathan <swavijay at gmail.com> wrote:
>     for i in range(10):
>         MyThread_Object.start()
>     count = threading.activeCount()
>
> When I run this, I could see 10 thread being called. But when I print the
> active thread count it is only 2.
>
> Need some understanding on the following.
>
> 1. How the total active thread is 2?

My guess is that all (or all but one) of the threads have finished
already by the time you check activeCount. If you add a call to
time.sleep(1) in the run() method, you'll see 11 or 12 threads (your
main threads and 10 others). If you print out threading.activeCount()
at the top of the program, you'll see that it starts at 2 in IDLE, or
1 in stand-alone Python.

> 2. how do I stop a thread? does it get automatically stopped after execution

Once the run() method returns, the thread is terminated. You shouldn't
normally need to stop a thread from another thread.

> 3. Am I totally wrong in understanding the concepts.
> 4. what is the difference between active_count() and activeCount() since
> both seem to give the same result.

The camelCase function names were inspired by Java's API, the ones
with underscores are more Python's style. They are absolutely the same
though. See the notes at the top of
http://docs.python.org/library/threading.html for that and other
information.

> 5. is there a way to find out if the thread is still active or dead?

Yep! Call is_alive() on your thread object. It'll return True if it's
still going. Again, the docs for the threading module
(http://docs.python.org/library/threading.html) have all that sort of
thing.

Threading is a bit of a tricky concept, and takes some getting used
to. There are many places where threads are awesome, and many where
they're pretty useless. The place I most often use threads is in
socket programming; when I run a server, I usually spin off a thread
to handle each incoming socket, as it's the easiest way to handle
sequential actions (especially if the socket protocol is
command-response, like a MUD or a mail server).

Once you get your head around the threading module, you'll find the
multiprocessing module very similar.  For Python, the difference is
sometimes quite important, so it's as well to understand both.

Hope that helps!

Chris Angelico



More information about the Python-list mailing list