私は約4つの入力テキストファイルを読み込み、すべてを1つの別々のファイルに書きたいと思っています。 私は2つのスレッドを使用するので、より速く実行されます!
私の質問とPythonのコードです:
1 - 各スレッドは "writeInFile"関数内に "lines"などの独自のバージョンの変数を持っていますか?
2 - Tutorialspointのコードの一部をコピーしたので、最後の行で "while 1:pass"が何か分かりません。説明できますか? http://www.tutorialspoint.com/python/python_multithreading.htm
3 - 私はスレッドにどのような遅延を置くかは重要ですか?
4 - 私が約400の入力テキストファイルを持っていて、それらのすべてを別々のファイルに書き込む前にいくつかの操作をしたい場合、使用できるスレッドの数はいくつですか?
5つのスレッドを使用すると仮定すると、入力が異なるフォルダ(それぞれ40個の入力テキストファイルがある10個のフォルダ)にあり、スレッドごとに1つのフォルダが呼び出されるか、既に以下のコードそれ以前に他のスレッドで読み込まれていない場合は、各スレッドに400個の入力テキストファイルの1つを読み込ませるように頼んでいますか?
Pythonでいくつかのスレッドを使って1つのメソッドを呼び出す
processedFiles=[] # this list to check which file in the folder has already been read by one thread so the other thread don't read it
#Function run by the threads
def writeInFile(threadName, delay):
for file in glob.glob("*.txt"):
if file not in processedFiles:
processedFiles.append(file)
f = open(file,"r")
lines = f.readlines()
f.close()
time.sleep(delay)
#open the file to write in
f = open('myfile','a')
f.write("%s \n" %lines)
f.close()
print "%s: %s" % (threadName, time.ctime(time.time()))
# Create two threads as follows
try:
f = open('myfile', 'r+')
f.truncate()
start = timeit.default_timer()
thread.start_new_thread(writeInFile, ("Thread-1", 0,))
thread.start_new_thread(writeInFile, ("Thread-2", 0,))
stop = timeit.default_timer()
print stop - start
except:
print "Error: unable to start thread"
while 1:
pass
返信ありがとうございます –