Python使用functools实现注解同步方法

yipeiwu_com6年前Python基础

在 Python 中没有类似 Java 中使用的 synchronized 关键字来同步方法,因此在 Python 中要实现同步方法,通常我们是使用 threading.Lock() 来实现。在进入函数的地方获取锁,出函数的时候释放锁,这样实现代码看起好非常不好看。另外网上也有人给出了其它几种实现方式,但看起来都不美气。

今天我在做项目的时候突然想到是不是可以通过 functools 来实现通过注解来标注方法为同步方法。

首先要求自己的类中有一个锁对象并且在类初始化的时候初始化这个锁对象,比如:

class MyWorker(object):
  def __init__(self):
    self.lock = threading.Lock()
    ...
  ...

然后创建一个 synchronized 函数,这个函数装饰具体对象的具体方法,将方法放到获取/释放锁之间来运行,如下

def synchronized(func):
  @functools.wraps(func)
  def wrapper(self, *args, **kwargs):
    with self.lock:
      return func(self, *args, **kwargs)
  return wrapper

最后在需要使用同步的方法上使用 @synchronized 来标准方法是同步方法,比如:

@synchronized
def test(self):
  ...

下面是一个完整例子,仅供参考:

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()

总结

以上所述是小编给大家介绍的Python使用functools实现注解同步方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

解决python 无法加载downsample模型的问题

downsample 在最新版本里面修改了位置 from theano.tensor.single import downsample (旧版本) 上面以上的的import会有error...

PyQT实现菜单中的复制,全选和清空的功能的方法

PyQt的文本操作的继承关系: QTextBrowser ( QtGui.QTextEdit) 其中QTextEdit具有的功能函数: copy() 复制 selectAll() 全选...

Python 3.6 -win64环境安装PIL模块的教程

Python 3.6 -win64环境安装PIL模块的教程

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。 由于PIL仅支持到Python 2.7...

python发送邮件示例(支持中文邮件标题)

复制代码 代码如下:def sendmail(login={},mail={}):    '''\    @param log...

Python读取Json字典写入Excel表格的方法

Python读取Json字典写入Excel表格的方法

需求: 因需要将一json文件中大量的信息填入一固定格式的Excel表格,单纯的复制粘贴肯定也能完成,但是想偷懒一下,于是借助Python解决问题。 环境: Windows7 +Pyth...