Leinad177
Leinad177

Reputation: 51

How to end a program properly with threads?

I have a class which pulls items from a queue and then runs code on it. I also have code in the main function that adds items to the queue for processing.

For some reason, the program doesn't want to end properly.

Here is the code:

class Downloader(Thread):

    def __init__(self, queue):
        self.queue = queue
        Thread.__init__(self)

    def run(self):
        while True: 
            download_file(self.queue.get())
            self.queue.task_done()

def spawn_threads(Class, amount):   
    for t in xrange(amount): 
        thread = Class(queue)
        thread.setDaemon = True
        thread.start()

if __name__ == "__main__":
    spawn_threads(Downloader, 20)
    for item in items: queue.put(item)
    #not the real code, but simplied because it isn't relevant

    print 'Done scanning. Waiting for downloads to finish.'
    queue.join()
    print 'Done!'

The program waits for it to finish properly at the queue.join() and prints Done!, but something keeps the program from closing which i can't seem to put my finger on. I'd assume it was the while True loop, but i thought setting the threads as daemons was meant to solve that.

Upvotes: 2

Views: 135

Answers (1)

NPE
NPE

Reputation: 500177

You are not using setDaemon() correctly. As a result, none of the Downloader threads are daemon threads.

Instead of

thread.setDaemon = True

write

thread.setDaemon(True)

or

thread.daemon = True

(The docs seem to imply that the latter is the preferred spelling in Python 2.6+.)

Upvotes: 2

Related Questions