我在apache2上有一个WSGI应用程序,它以最简单的方式写入日志文件:
def log (msg):
with open (LOGFILE, 'a') as f: f.write (msg)
在我的沙箱环境中,它工作正常,但我对并发性有点担心。如果apache2运行各种线程,我是否必须担心并发问题?也许我的日志文件会被扰乱?如果另一个线程已经记录,可能会调用log (msg)
失败吗?如果是这种情况,我该怎样阻止它?
修改 为了测试,我从两个shell同时运行两个脚本:
#! /usr/bin/python3.2
def log ():
with open ('log', 'a') as f:
f.write ('message from thread A\n')
while (True): log ()
和
#! /usr/bin/python3.2
def log ():
with open ('log', 'a') as f:
f.write ('message from thread B\n')
while (True): log ()
日志文件看起来很好,没有发生错误。我是幸运还是从两个不同的线程写入同一个文件是安全的。文件系统是ext4。