[Tutor] Threading in a for loop

Bill Burns billburns at pennswoods.net
Tue Sep 20 22:06:06 CEST 2005

I've got a few questions regarding Threading. I've never used threads
before and I want to make sure I'm doing it correctly ;-)

I have a GUI app and it processes Tiff files to PDF (or PostScript). The
GUI has a ListBox which the user populates with files to convert. You
click on a Button and the file conversion starts. When all the files
have been converted, the ListBox items (the files) are cleared.

Initially, you had no way of knowing what was going on until all the
files where cleared from the ListBox.

So I thought of creating threads in the 'for loop' and displaying the
name of each file in the statusBar of the GUI (as they are being

Here's my method which takes the files in the ListBox and sends them off
to my Convert() class (self.convert = Convert()).
def convertTiff2PDF(self):
     from time import time
     #Let's see how long this takes... I saw Kent do this on the
     #Python Tutor list before :-)
     start = time()
     #Grab a tuple which contains width & length
     sizes = self.getPaperSize()
     width = sizes[0]
     length = sizes[1]
     #Count the number of files in the ListBox
     fileCount = self.fileListBox.count()
     for index in range(fileCount):
         #Get each filename
         filenames = str(self.fileListBox.text(index))
         #Setup the worker thread and send the filenames in
         worker = WorkerThread(self, filenames)
         #Start threading
         #Send each file to be converted
         self.convert.tiff2pdf(width, length, filenames)
     #We're done, so clear the ListBox
     #Check the time again
     end = time()
     msg = '%s Files Processed in %0.3f Seconds.' % (fileCount,
     #Grab the statusBar and insert the message
     statusBar = self.statusBar()
     statusBar.message(msg, 0)

And here's what I'm doing in my Thread class:
class WorkerThread(Thread):
     """Thread class."""
     def __init__(self, parent, files):
         self.parent = parent
         self.files = files

     def run(self):
         statusBar = self.parent.statusBar()
         msg = 'Processing: %s, please wait.' % (self.files)
         statusBar.message(msg, 100)

Am I doing this threading properly? Is it 'OK' to start multiple threads
like this (in the for loop)? It's possible that a user could put 'many'
files into the ListBox, by 'many' I mean 100-200 files.

Thanks for your help.


More information about the Tutor mailing list