带队列的Python多线程

时间:2014-07-27 13:50:38

标签: python multithreading

这是我的代码;

import threading
from Queue import Queue



words = open("words.txt")


lock = threading.Lock()
threads = 10


q = Queue(maxsize=0)


def myfunction(q):
    lock.acquire()
    print q.get()
    lock.release()
    q.task_done()


for x in range(threads):
    m = threading.Thread(target=myfunction, args=(q,))
    m.setDaemon(True)
    m.start()

for word in words:
    q.put(word.strip())




q.join()

raw_input()

这将输出:

word1
word2
word3
word4
word5
word6
word7
word8
word9
word10

然后它会停止。文件中还有更多单词,我怎样才能继续?根据我的理解,q.join()应该等到队列为空以添加更多。

我想把它放在这样的循环中:

for word in words:
    q.put(word.strip())
    for x in range(threads):
        m = threading.Thread(target=myfunction, args=(q,))
        m.setDaemon(True)
        m.start()

但我有时会收到一条错误,说“无法启动新主题”。

1 个答案:

答案 0 :(得分:2)

您的线程在处理完一个队列项后就完成了。

将工作程序代码(即myfunction的正文)放入while: True循环中,以便它不断从队列中获取更多项目,而不是在调用q.task_done()后返回。

相关问题