2

我正在尝试调试使用各种锁的多线程 Python 应用程序。

我的想法是装饰方法threading.Lock.acquire ()threading.Lock.release () , 并在其调用前加上以下内容:

log.debug("lock::acquire() [%s.%s.%s]" %
          (currentThread().getName(),
           self.__class__.__name__,
           sys._getframe().f_code.co_name))

其中log是一些全局日志记录对象-为了讨论。

现在理想情况下,日志条目中的名称“lock”应该在运行时派生,因此无论在日志上调用哪个锁对象,这些方法都将输出其名称、修饰的操作、当前线程、类和函数调用操作 (acquire | release)。

免责声明:我承认上面给出的代码对于任何这样的装饰器实现都是不够的。提供它只是为了说明我认为可以实现的目标。

有谁知道我是否可以装饰标准库方法,而无需修改线程库的原始源代码,即从我的调用应用程序代码中?

也许我在吠叫错误的树,并且有更好的方法来实现相同的目的,而不使用装饰器?如果确实如此,请提前非常感谢您的任何指导。

解决方案:(灵感来自lazyr)

以下代码记录了锁定操作,并为我提供了调用锁定操作的方法/函数的名称(我也在调整代码以使用条件及其附加的wait()notify()方法):

# Class to wrap Lock and simplify logging of lock usage
class LogLock(object):
    """
    Wraps a standard Lock, so that attempts to use the
    lock according to its API are logged for debugging purposes

    """
    def __init__(self, name, log):
        self.name = str(name)
        self.log = log
        self.lock = threading.Lock()
        self.log.debug("{0} created {1}".format(
            inspect.stack()[1][3], self.name))

    def acquire(self, blocking=True):
        self.log.debug("{0} trying to acquire {1}".format(
            inspect.stack()[1][3], self.name))
        ret = self.lock.acquire(blocking)
        if ret == True:
            self.log.debug("{0} acquired {1}".format(
                inspect.stack()[1][3], self.name))
        else:
            self.log.debug("{0} non-blocking acquire of {1} lock failed".format(
                inspect.stack()[1][3], self.name))
        return ret

    def release(self):
        self.log.debug("{0} releasing {1}".format(inspect.stack()[1][3], self.name))
        self.lock.release()

    def __enter__(self):
        self.acquire()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.release()
        return False # Do not swallow exceptions

日志实例传递给 LogLock 的位置。init是用logging.Formatter定义的,如下所示给我调用线程的身份:

# With the following format
log_format = \
        logging.Formatter('%(asctime)s %(levelname)s %(threadName)s %(message)s')
4

1 回答 1

5

我最近遇到了你的问题。我将记录器设置为自动记录线程名称,就像在这个答案中一样。我发现不可能将 Lock 子类化,所以我不得不将它包装起来,如下所示:

class LogLock(object):
    def __init__(self, name):
        self.name = str(name)
        self.lock = Lock()

    def acquire(self, blocking=True):
        log.debug("{0:x} Trying to acquire {1} lock".format(
            id(self), self.name))
        ret = self.lock.acquire(blocking)
        if ret == True:
            log.debug("{0:x} Acquired {1} lock".format(
                id(self), self.name))
        else:
            log.debug("{0:x} Non-blocking aquire of {1} lock failed".format(
                id(self), self.name))
        return ret

    def release(self):
        log.debug("{0:x} Releasing {1} lock".format(id(self), self.name))
        self.lock.release()

    def __enter__(self):
        self.acquire()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.release()
        return False    # Do not swallow exceptions

我记录了对象的 ID,因此我可以区分多个具有相同名称的锁,您可能不需要它。

于 2011-03-16T15:45:39.007 回答