マルチスレッド関数があり、すべてが同じログ ファイルに書き込まれます。ログファイルへの書き込みの実行をキューに追加するために、この関数を(おそらく関数デコレータを使用して)作成するにはどうすればよいですか。小さな例:
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
writeToLog(threadName, time.ctime(time.time()))
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
def writeToLog(threadName, time):
self.fileWriter = open("log.txt", "w")
self.fileWriter.write("ThreadName: " + threadName + "\n")
self.fileWriter.write("Time: " + time + "\n")
self.fileWriter.close()
実行時にこの関数 writeToLog をキューに追加するにはどうすればよいですか? 他の writeToLog 関数 (他のスレッドから) が既にファイルを閉じているため、両方のスレッドが writeToLog 関数を呼び出すたびにエラーが発生します。最終的に閉じられるこのライターのグローバル変数がある場合、次のような出力が得られます。
ThreadName: thread1
ThreadName: thread2
Time: 9:50AM
Time: 9:50AM
そして、私が常に望む出力は次のようになります。
ThreadName: Thread-1
Time: 9:50AM
ThreadName: Thread-2
Time: 9:50AM