0

マルチスレッド関数があり、すべてが同じログ ファイルに書き込まれます。ログファイルへの書き込みの実行をキューに追加するために、この関数を(おそらく関数デコレータを使用して)作成するにはどうすればよいですか。小さな例:

#!/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
4

1 に答える 1

2

共有リソースへの同時アクセスはよく知られている問題です。Python スレッドは、問題を回避するためのメカニズムを提供します。Python ロックを使用します: http://docs.python.org/2/library/threading.html#lock-objects ロックは共有リソースへのアクセスを同期するために使用されます:

lock = Lock()

lock.acquire() # will block if lock is already held
... access shared resource
lock.release()

詳細: http://effbot.org/zone/thread-synchronization.htm

「Python 同期」を検索

于 2013-08-20T07:56:55.007 に答える