首页 > 代码库 > python装饰器实现线程同步
python装饰器实现线程同步
import threading
def tryfinally(finallyf):
u"returns a decorator that adds try/finally behavior with given no-argument call in the finally"
print "tryfinally"
def decorator(callable):
print "decorator"
def execute(*args, **kwargs):
print "execute1"
try: result = callable(*args, **kwargs)
finally: finallyf()
return result
return execute
return decorator
def usinglock(lock):
u"returns a decorator whose argument will acquire the given lock while executing"
print "usinglock"
def decorator(function):
print "decorator"
body = tryfinally(lock.release)(function)
def execute(*args, **kwargs):
print "execute"
lock.acquire()
return body(*args, **kwargs)
return execute
return decorator
def synchronized(function):
u"decorator; only one thread can enter the decorated function at a time; recursion is OK"
print "synchronized"
return usinglock(threading.RLock())(function)
@synchronized
def foo(*args):
print "Only one thread can enter this function at a time"
if __name__=="__main__":
foo(123)
def tryfinally(finallyf):
u"returns a decorator that adds try/finally behavior with given no-argument call in the finally"
print "tryfinally"
def decorator(callable):
print "decorator"
def execute(*args, **kwargs):
print "execute1"
try: result = callable(*args, **kwargs)
finally: finallyf()
return result
return execute
return decorator
def usinglock(lock):
u"returns a decorator whose argument will acquire the given lock while executing"
print "usinglock"
def decorator(function):
print "decorator"
body = tryfinally(lock.release)(function)
def execute(*args, **kwargs):
print "execute"
lock.acquire()
return body(*args, **kwargs)
return execute
return decorator
def synchronized(function):
u"decorator; only one thread can enter the decorated function at a time; recursion is OK"
print "synchronized"
return usinglock(threading.RLock())(function)
@synchronized
def foo(*args):
print "Only one thread can enter this function at a time"
if __name__=="__main__":
foo(123)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。