在python中为函数创建队列,使其一次只运行一次

在python中为函数创建队列,使其一次只运行一次,python,multithreading,Python,Multithreading,我有一个多线程函数,它们都写入同一个日志文件。如何使这个函数(可能带有函数装饰器)将写入日志文件的执行添加到队列中。 小例子: #!/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) cou

我有一个多线程函数,它们都写入同一个日志文件。如何使这个函数(可能带有函数装饰器)将写入日志文件的执行添加到队列中。 小例子:

#!/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()
我一直想要的输出是这样的:

ThreadName: thread1
ThreadName: thread2
Time: 9:50AM
Time: 9:50AM
ThreadName: Thread-1
Time: 9:50AM
ThreadName: Thread-2
Time: 9:50AM

对共享资源的并发访问是一个众所周知的问题。Python线程提供了一些避免问题的机制。 使用python锁: 锁用于同步对共享资源的访问:

lock = Lock()

lock.acquire() # will block if lock is already held
... access shared resource
lock.release()
更多信息:


搜索“Python同步”

为什么不使用Python
logging
,这是为了线程安全而设计的?@RapolasK。我是python新手,从未见过这个模块,看起来非常方便。我想我现在将使用这个模块,而不是我自己的类。谢谢谢谢,这是我问题的正确答案,所以我会接受这个答案。但是我现在要使用日志模块。
Lock
实例是一个,它允许您使用Lock编写
然后
。。。访问共享资源
,而不访问其他内容。退出缩进块时,
release()
将自动发生,即使发生这种情况是因为发生了异常或执行了
return
语句。