multithreading in python

Dave Angel davea at davea.name
Tue Aug 13 07:40:27 EDT 2013


samaneh.yahyapour at gmail.com wrote:

> hi 
> my program work by 4 thread but when i use more thread it terminates
>    <snip>
> how can i solve this problem 

I simplified the code so I could actually run it, and tested it in
Python 2.7, both under Komodo IDE and in the terminal.

The code:

#!/usr/bin/env python


import sys
import os
import time
import threading

class MyClass():

    def __init__(self):
        self.threads = []
        i = 0
        while i<10:
            work = WorkClass(i)
            thread1 = threading.Thread(target=work.item_thread)
            self.threads.append(thread1)
            thread1.start()
            i = i+1
            time.sleep(0.01)
        for thread in self.threads:   #wait for all the threads to end
            thread.join()

class WorkClass():
    def __init__(self, parm):
        self.parm = str(parm)
    def item_thread(self):
        print "beginning thread", self.parm
        for filename in os.listdir("."):
            data =  "thread " +  self.parm + " filename " + filename + "\n"
            print data
            time.sleep(0.5)
        print "ENDDDDDDDDDDDDDDDDDDDDDDDDDDDD " + self.parm

x = MyClass()         
print "All done with main thread"

The original code couldn't tell us what threads were running, so the
only clue you got was how many times it printed "ENDDDD"  So I arranged
that each thread had a unique "parm" value.  Typically you must do
something like this so that all the threads aren't doing exactly the
same work.

Another thing i did was to "atomicize" the print statements.  As it
originally was, partial lines from different threads could be
intermixed in the output.

The IDE showed the error message:

"""
ERROR: dbgp.client: 
The main thread of this application is exiting while there are still threads
alive. When the main thread exits, it is system defined whether the other
threads survive.

See Caveats at http://docs.python.org/lib/module-thread.html
"""

which tells you what's wrong.  You need to do a join on the threads
before exiting.

it's traditional (and better) to derive your own class from
threading.Thread, and that's where you can store any additional
attributes that each thread will need. I demonstrated something I
figured was simpler, by making the item_thread() method part of a
separate class.

-- 
DaveA





More information about the Python-list mailing list