我有一个多线程函数,它都写入同一个日志文件。如何将此函数(可能带有函数装饰器)添加到日志文件中的写入执行添加到队列中。 小例子:
#!/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
答案 0 :(得分: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同步”