【问题标题】:Python multi threading with queue带队列的 Python 多线程
【发布时间】:2014-07-27 13:50:38
【问题描述】:

这是我的代码;

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()

但我有时会收到“无法启动新线程”的错误消息。

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    您的线程在处理完一个队列项后才结束。

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

    【讨论】:

    • 这修复了它。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多