NewBie Doubt in Python Thread Programming

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed May 11 03:31:50 EDT 2011


En Wed, 11 May 2011 03:57:13 -0300, vijay swaminathan <swavijay at gmail.com>  
escribió:

> Hi All,
>
> I'm new bie to thread programming and I need some assistance in
> understanding few concepts ...
>
> I have a very simple program which runs a thread and prints a string.
>
> import threading
>
> class MyThread(threading.Thread):
>     def __init__(self, parent = None):
>         threading.Thread.__init__(self)
>
>     def run(self):
>         print 'Hello World'
>
> def main():
>     for i in range(10):
>         MyThread_Object = MyThread()
>         print 'Object id is : ' , id(MyThread_Object)
>         print 'Staring thread ----------> ' , MyThread_Object.getName()
>         MyThread_Object.start()
>     count = threading.activeCount()
>     print 'The active thread count is: ' , count
>
> if __name__ == '__main__':
>     main()
>
> 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?

Because most of them have already finished by then. Your run() method  
executes quite fast. Make it take more time (maybe by adding  
time.sleep(1)) and you'll see 10 active threads.

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

You don't; a trhread runs until the run() method exits. After that, the OS  
thread finishes. The Python object (a threading.Thread instance) is still  
alive (until the last reference to it disappears, as any other object).

> 3. Am I totally wrong in understanding the concepts.

I don't know...

> 4. what is the difference between active_count() and activeCount() since
> both seem to give the same result.

Nothing. active_count is the preferred Python spelling per PEP8;  
activeCount is the original Java spelling.

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


Yes, use is_alive()

-- 
Gabriel Genellina




More information about the Python-list mailing list