简体   繁体   中英

Threading / Queue in Python

I intend using threads/queues with python 2.5.2 But it seems that python becomes freezed at the queue.join()-command. The output of the followong code is only: BEFORE

import Queue
import threading

queue = Queue.Queue()

class ThreadUrl(threading.Thread):

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

    def run(self):
        while True:

            i = self.queue.get()
            print i
            self.queue.task_done()


def main():

    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    for i in range(5):
        queue.put(i)

    print "BEFORE"
    queue.join()
    print "AFTER"


main()

Has someone an idea about what is going wrong?

I think it is the t.setDaemon(True) part.

So in Python > 2.6, use:

t.setDaemon(True)

And in Python < 2.6, use:

t.daemon = True

Use Daemon=True. That will ensure that your thread exits once the main function is executed.

You run() method on your ThreadUrl class is indented too far. The thread is never started as a result. If you put the indention of the run method at the same indentation level as init () it'll work fine.

The solution I now found is:

Don't use Python 2.5.2. If one uses Python 2.7.2 instead the code above works very well.

Thank you all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM