我创建了5个线程来处理这些行。我发送一行作为每个线程的参数。迭代文件但每次迭代需要5行
输出就是我需要的。但是,它会因错误而停止。
代码:
#!usr/bin/env python3
# -*- coding: UTF-8 -*-
import threading
# Create class myThread as subclass of Thread
class MyThread(threading.Thread):
def __init__(self, num, myArg):
threading.Thread.__init__(self)
self.num = num
self.myArg = myArg
# Overrides run() method to defines the thread goes to do.
def run(self):
print ("I'm thread number: ", self.num)
print(self.myArg)
myFile = open('file_01.txt', mode='r')
for myLine in myFile:
for h in range(1, 6): # create 5 instances of the thread
t = MyThread(h, myLine)
t.start()
myLine = myFile.__next__()
myFile.close()
错误:
Traceback (most recent call last):
File "/sajime/PycharmProjects/Learning/iterarFichero.py", line 25, in <module>
myLine = myFile.__next__()
StopIteration
的 'file_01.txt' 的内容是一个简单的 'Lorem存有悲坐阿梅德,...' 的东西。
该错误不在多线程类中,也没有调用,它出现在文件的迭代中,但是,为什么?
对于那些谁是问为什么我需要这样的:脚本必须处理线加载在Web表单数据,并采取了很多的时间(滞后于服务器)。我意识到,如果我分工的任务更快。 (我不知道是否有更好的方法来做到这一点)
这是有点不清楚你想要做什么。您的文件中可以有多少行?你想要多少个线程?这听起来像你想要5个线程,但它看起来像你正在为文件中的每一行创建一个线程。 – Weeble
@Weeble文件中的行是未知的。有5个线程。是的,我为文件中的每一行创建一个线程,但同时只有5个线程正在工作。 – Trimax
为什么不能有5个线程并通过队列发送线路?顺便说一下,在Python中,严格来说,即使在多核机器上,只有一个线程可以同时工作*。 – bereal