码迷,mamicode.com
首页 > 编程语言 > 详细

python装饰器实现线程同步

时间:2014-08-05 11:17:29      阅读:226      评论:0      收藏:0      [点我收藏+]

标签: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)

python装饰器实现线程同步,布布扣,bubuko.com

python装饰器实现线程同步

标签:python

原文地址:http://blog.csdn.net/fanyunlei/article/details/38380609

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!