我有一个包含大量数据的文件。每一行都是一条记录。我正在尝试对整个文件进行一些ETL工作。现在我正在使用标准输入逐行读取数据。这很酷的事情是你的脚本可以非常灵活地与其他脚本和shell命令集成。我将结果写入标准输出。例如。Python Threading stdin/stdout
$ cat input_file
line1
line2
line3
line4
...
我当前的Python代码看起来是这样的 - parse.py
import sys
for line in sys.stdin:
result = ETL(line) # ETL is some self defined function which takes a while to execute.
print result
下面的代码是它是如何工作现在:
cat input_file | python parse.py > output_file
我已经看过了线程模块的Python,我想知道如果我使用该模块,性能会大大提高。
问题1:我该如何规划每个线程的配额,为什么?
...
counter = 0
buffer = []
for line in sys.stdin:
buffer.append(line)
if counter % 5 == 0: # maybe assign 5 rows to each thread? if not, is there a rule of thumb to determine
counter = 0
thread = parser(buffer)
buffer = []
thread.start()
问题2:多线程可能在同一时间打印出结果返回到标准输出,如何组织他们,避免下面的情况呢?
import threading
import time
class parser(threading.Thread):
def __init__ (self, data_input):
threading.Thread.__init__(self)
self.data_input = data_input
def run(self):
for elem in self.data_input:
time.sleep(3)
print elem + 'Finished'
work = ['a', 'b', 'c', 'd', 'e', 'f']
thread1 = parser(['a', 'b'])
thread2 = parser(['c', 'd'])
thread3 = parser(['e', 'f'])
thread1.start()
thread2.start()
thread3.start()
的输出是真难看,其中一个行都包含来自两个线程的输出。
aFinished
cFinishedeFinished
bFinished
fFinished
dFinished
你能链接“Python的线程模块”吗? 无论如何,线程访问一个文件,恕我直言,是不是一件好事。您需要定义什么内核可以通过锁和信号量以及作品访问什么以及何时访问。 由于大部分工作是I/O工作,而不是CPU工作,可能你不会看到性能提升。 –