Threading / Queue in Python

余生颓废 提交于 2019-12-08 09:01:43

问题


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?


回答1:


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

so > 2.6

t.setDaemon(True)

< 2.6

t.daemon = True




回答2:


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.




回答3:


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!




回答4:


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



来源:https://stackoverflow.com/questions/7074984/threading-queue-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!