我有这种情况:
threads = []
for wordToScan in wordsList:
dictionaryFileOpen = open(dictionaryFile, "r")
for i in range(10):
threads.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
def words_Scan_Start(dictionaryFile, wordToScan):
while True:
sub_word = dictionaryFile.readline()
if not sub_word:
break
#... Here is some actions.
现在我需要立即启动所有这些线程(每个wordToScan in wordsList
分别有10个线程。)
每个wordToScan in wordsList:
应该在10个主题中使用dictionaryFileOpen
,但不会为同时工作的其他.readline()
移动wordToScan in wordsList:
。另外,我无法理解关闭dictionaryFileOpen
的位置。
答案 0 :(得分:0)
以下是我完成的工作:
threads = []
for wordToScan in wordsList:
wordThread = []
dictionaryFileOpen = open(dictionaryFile, "r")
for i in range(10):
wordThread.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan)))
threads.append(wordThread)
for thread in threads:
for wordThread in thread:
wordThread.start()
for thread in threads:
for wordThread in thread:
wordThread.join()
dictionaryFileOpen.close()
def words_Scan_Start(dictionaryFile, wordToScan):
while True:
sub_word = dictionaryFile.readline()
if not sub_word:
break
#... Here is some actions.
我做得对吗?
答案 1 :(得分:0)
您不应该从多个线程中读取文件。这涉及以下注意事项:
因此,一般方法是从一个线程读取文件,然后为其他线程调度处理分支。如果你能在一个线程中完成工作,最好这样做,因为它更简单。只有在你真正需要时才能创建多线程应用程序。