Python使用functools实现注解同步方法
在Python中没有类似Java中使用的synchronized关键字来同步方法,因此在Python中要实现同步方法,通常我们是使用threading.Lock()来实现。在进入函数的地方获取锁,出函数的时候释放锁,这样实现代码看起好非常不好看。另外网上也有人给出了其它几种实现方式,但看起来都不美气。
今天我在做项目的时候突然想到是不是可以通过functools来实现通过注解来标注方法为同步方法。
首先要求自己的类中有一个锁对象并且在类初始化的时候初始化这个锁对象,比如:
classMyWorker(object): def__init__(self): self.lock=threading.Lock() ... ...
然后创建一个synchronized函数,这个函数装饰具体对象的具体方法,将方法放到获取/释放锁之间来运行,如下
defsynchronized(func): @functools.wraps(func) defwrapper(self,*args,**kwargs): withself.lock: returnfunc(self,*args,**kwargs) returnwrapper
最后在需要使用同步的方法上使用@synchronized来标准方法是同步方法,比如:
@synchronized deftest(self): ...
下面是一个完整例子,仅供参考:
importthreading importfunctools importtime defsynchronized(func): @functools.wraps(func) defwrapper(self,*args,**kwargs): withself.lock: returnfunc(self,*args,**kwargs) returnwrapper classMyWorker(object): def__init__(self): self.lock=threading.Lock() self.idx=0 @synchronized deftest1(self): foriinrange(1,11): self.idx=self.idx+1 print"Test1:"+str(self.idx) time.sleep(1) @synchronized deftest2(self): foriinrange(1,11): self.idx=self.idx+1 print"Test2:"+str(self.idx) time.sleep(1) @synchronized deftest3(self): foriinrange(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()
总结
以上所述是小编给大家介绍的Python使用functools实现注解同步方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!