zoukankan      html  css  js  c++  java
  • 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)

    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    JVM底层原理 内存模型+GC垃圾回收
    新Socket与网络小结
    Redis五大数据结构及基本指令用法
    MySql高级汇总-事务,索引,SQL调优,分库分表,读写分离
    笔试错题整理
    设计模式(思路)
    网络编程
    linux
    基础算法--KMP匹配字符串
    基础算法--整数二分
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4907195.html
Copyright © 2011-2022 走看看