



时间:2018-02-06 关注公众号 来源:网络
在 Python 中没有类似 Java 中使用的 synchronized 关键字来同步方法,因此在 Python 中要实现同步方法,通常我们是使用 threading.Lock() 来实现。在进入函数的地方获取锁,出函数的时候释放锁,这样实现代码看起好非常不好看。另外网上也有人给出了其它几种实现方式,但看起来都不美气。
今天我在做项目的时候突然想到是不是可以通过 functools 来实现通过注解来标注方法为同步方法。
首先要求自己的类中有一个锁对象并且在类初始化的时候初始化这个锁对象,比如:
?
1 2 3 4 5 | Stream Vera Sans Mono', 'Courier New', Courier, monospace !important; float: none !important; border-top-width: 0px !important; border-bottom-width: 0px !important; height: auto !important; color: rgb(0, 102, 153) !important; vertical-align: baseline !important; overflow: visible !important; top: auto !important; right: auto !important; font-weight: bold !important; left: auto !important; background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;" class="py keyword">class MyWorker( object ): def __init__( self ): self .lock = threading.Lock() ... ... |
然后创建一个 synchronized 函数,这个函数装饰具体对象的具体方法,将方法放到获取/释放锁之间来运行,如下
?
1 2 3 4 5 6 | def synchronized(func): @functools .wraps(func) def wrapper( self , * args, * * kwargs): with self .lock: return func( self , * args, * * kwargs) return wrapper |
最后在需要使用同步的方法上使用 @synchronized 来标准方法是同步方法,比如:
?
1 2 3 | @synchronized def test( self ): ... |
下面是一个完整例子,仅供参考:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import threading import functools import TIMe def synchronized(func): @functools .wraps(func) def wrapper( self , * args, * * kwargs): with self .lock: return func( self , * args, * * kwargs) return wrapper class MyWorker( object ): def __init__( self ): self .lock = threading.Lock() self .idx = 0 @synchronized def test1( self ): for i in range ( 1 , 11 ): self .idx = self .idx + 1 print "Test1: " + str ( self .idx) time.sleep( 1 ) @synchronized def test2( self ): for i in range ( 1 , 11 ): self .idx = self .idx + 1 print "Test2: " + str ( self .idx) time.sleep( 1 ) @synchronized def test3( self ): for i in range ( 1 , 11 ): self .idx = self .idx + 1 print "Test3: " + str ( self .idx) time.sleep( 1 ) worker = MyWorker() threading.Thread(target = worker.test1).start() threading.Thread(target = worker.test2).start() threading.Thread(target = worker.test3).start() |
文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站)
电话:13918309914
QQ:1967830372
邮箱:rjfawu@163.com