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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值