【发布时间】: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