首页 > 其他 > 详细

LockFile文件-解决并发写入日志的问题

时间:2021-04-14 15:48:51      阅读:17      评论:0      收藏:0      [点我收藏+]
import threading
import os


class LockedFile(object):
    SETUP_LOGGER_LOCK = threading.Lock()
    LOGFILES = {}

@classmethod
def open(cls, fn):
    with cls.SETUP_LOGGER_LOCK:
        if fn not in cls.LOGFILES:
            if os.path.exists(os.path.dirname(fn)):
                os.mkdir(os.path.dirname(fn))
                cls.LOGFILES[fn] = cls(fn)
        rv = cls.LOGFILES[fn]
        rv.users += 1
    return rv

def __init__(self, fn):
    self._filename = fn
    self._f = None
    self.users = 0
    self._lock = threading.Lock()

def __enter__(self):
    return self

def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

def write(self, data):
    with self._lock:
        if self._f is None:
            self._f = open(self._filename, ‘ab‘)
        self._f.write(data)
        self._f.flush()

def close(self):
    with self.SETUP_LOGGER_LOCK:
        self.users -= 1
        if self.users == 0:
            if self._f:
                self._f.close()
            self.LOGFILES.pop(self._filename)

LockFile文件-解决并发写入日志的问题

原文:https://www.cnblogs.com/Ghostant/p/14656642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!