我有一个多线程函数,它们都写入同一个日志文件。我怎样才能使这个函数(可能使用函数装饰器)来将写入日志文件的执行添加到队列中。小例子:
#!/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 函数(来自另一个线程)已经关闭了文件。当这个 writer 有一个全局变量时,它最终是关闭的,我得到这样的输出:
ThreadName: thread1
ThreadName: thread2
Time: 9:50AM
Time: 9:50AM
我一直想要的输出必须是这样的:
ThreadName: Thread-1
Time: 9:50AM
ThreadName: Thread-2
Time: 9:50AM