开发者

Threading / Queue in Python

开发者 https://www.devze.com 2023-03-28 04:02 出处:网络
I intend using threads/queues with python 2.5.2 But it seems that python becomes freezed at the queue.join()-command.

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 "AFTE开发者_运维知识库R"


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


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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号