开发者

mutex decorator in python

I saw this: http://yukelzon.blogspot.com/2005/07/python-locks.html when looking for a solution to add some locking to existing code around writing to a file.

The simplified version for my needs looks like this:

  def mlock(orig):
    def inner(*args, **kwargs):
      Coloring.lock.acquire()
      try:
        ret = orig(*args, **kwargs)
    开发者_C百科    return ret
      finally:
        Coloring.lock.release()
    return inner

The lock is a class variable. Can any one think of improvements or better ways?


If you're using Python 2.6+ (I think), mutex objects are context managers, so:

def mlock(f):
    def inner(*args, **kwargs):
        with Coloring.lock:
            return f(*args, **kwargs)
    return inner


I'm not a fan of free variables. I would probably make the lock an explicit variable of the decorator, like so:

def mlock(Coloring):
    def mlock_decorator(orig):
        def inner(*args, **kwargs):
          Coloring.lock.acquire()
          try:
            ret = orig(*args, **kwargs)
            return ret
          finally:
            Coloring.lock.release()
        return inner
    return mlock_decorator

Well, since Coloring is a class variable, and if you expect this to be pretty specific to that class, access it explicitly:

def mlock(orig):
    def inner(self, *args, **kwargs):
      self.Coloring.lock.acquire()
      try:
        ret = orig(self, *args, **kwargs)
        return ret
      finally:
        self.Coloring.lock.release()
    return inner

Or, at very least, declare that the lock is a global

def mlock(orig):
    global Coloring
    def inner(*args, **kwargs):
      Coloring.lock.acquire()
      try:
        ret = orig(*args, **kwargs)
        return ret
      finally:
        Coloring.lock.release()
    return inner
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜