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 函数(来自另一个线程)已经关闭了文件。当这个 writer 有一个全局变量时,它最终是关闭的,我得到这样的输出:

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 回答