簡體   English   中英

帶隊列的Python多線程

[英]Python multi threading with queue

這是我的代碼;

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

但是有時我會收到一條錯誤消息,提示“無法啟動新線程”。

您的線程在處理完一個隊列項目后才結束。

將工作程序代碼(即myfunction的主體)放while: True循環,以便它繼續從隊列中獲取更多項目,而不是在調用q.task_done()返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM