python装饰实现线程同步
2015-10-24 17:11
573 查看
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)
相关文章推荐
- Python中转到指定目录
- Python3.5环境安装及使用 Speech问题解决
- Python学习笔记4
- Python学习笔记-变量和数据类型
- Python3便捷的操作——导入模块
- Python在信号与系统(1)——Hilbert兑换,Hilbert在国家统计局的包络检测应用,FIR_LPF滤波器设计,格鲁吉亚也迫使高FM(PM)调制
- Python实现机器学习一(实现一元线性回归)
- RHEL6.7下,安装Python3.5,进行编程开发
- Python下关于JSON的一些事儿
- leetcode之Set Matrix Zeroes
- What does the yield keyword do in Python?
- python 自动登录网站
- python socket编程
- Python机器学习库scikit-learn实践
- Python - 基础知识 - 条件判断
- python socket编程详细介绍
- Python repr() 或str() 函数
- Python内置的字符串处理函数整理
- 使用IronPython给.Net程序加点料
- Python if elif else语句