python 中的互斥装饰器
我看到了这个: http://yukelzon.blogspot.com/2005/07/python -locks.html 在寻找解决方案以向现有代码添加一些锁定以写入文件时。
满足我需要的简化版本如下所示:
def mlock(orig):
def inner(*args, **kwargs):
Coloring.lock.acquire()
try:
ret = orig(*args, **kwargs)
return ret
finally:
Coloring.lock.release()
return inner
锁是一个类变量。任何人都可以想到改进或更好的方法吗?
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)
return ret
finally:
Coloring.lock.release()
return inner
The lock is a class variable. Can any one think of improvements or better ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 Python 2.6+(我认为),互斥对象是上下文管理器,因此:
If you're using Python 2.6+ (I think), mutex objects are context managers, so:
我不喜欢自由变量。我可能会让锁成为装饰器的显式变量,如下所示:
好吧,因为 Coloring 是一个类变量,如果您希望它非常特定于该类,请显式访问它:
或者,至少声明该锁是全局的
I'm not a fan of free variables. I would probably make the lock an explicit variable of the decorator, like so:
Well, since
Coloring
is a class variable, and if you expect this to be pretty specific to that class, access it explicitly:Or, at very least, declare that the lock is a global