用Python实现读写锁

起步

Python 提供的多线程模型中并无提供读写锁,读写锁相对于单纯的互斥锁,适用性更高,能够多个线程同时占用读模式的读写锁,可是只能一个线程占用写模式的读写锁多线程

通俗点说就是当没有写锁时,就能够加读锁且任意线程能够同时加;而写锁只能有一个线程,且必须在没有读锁时才能加上。app

简单的实现

import threading

class RWlock(object):
    def __init__(self):
        self._lock = threading.Lock()
        self._extra = threading.Lock()
        self.read_num = 0

    def read_acquire(self):
        with self._extra:
            self.read_num += 1
            if self.read_num == 1:
                self._lock.acquire()

    def read_release(self):
        with self._extra:
            self.read_num -= 1
            if self.read_num == 0:
                self._lock.release()

    def write_acquire(self):
        self._lock.acquire()

    def write_release(self):
        self._lock.release()

这是读写锁的一个简单的实现,self.read_num 用来保存得到读锁的线程数,这个属性属于临界区,对其操做也要加锁,因此这里须要一个保护内部数据的额外的锁 self._extraide

可是这个锁是不公平的。理想状况下,线程得到所的机会应该是同样的,无论线程是读操做仍是写操做。而从上述代码能够看到,读请求都会当即设置 self.read_num += 1,无论有没有得到锁,而写请求想要得到锁还得等待 read_num 为 0 。ui

因此这个就形成了只有锁没有被占用或者没有读请求时,能够得到写权限。咱们应该想办法避免读模式锁长期占用。线程

读写锁的优先级

读写锁也有分 读优先写优先。上面的代码就属于读优先。code

若是要改为写优先,那就换成去记录写线程的引用计数,读和写在同时竞争时,可让写线程增长写的计数,这样可以使读线程的读锁一直获取不到, 由于读线程要先判断写的引用计数,若不为0,则等待其为 0,而后进行读。这部分代码不罗列了。rem

但这样显然不够灵活。咱们不须要两个类似的读写锁类。咱们但愿重构咱们代码,使它更强大。get

改进

为了可以知足自定义优先级的读写锁,要记录等待的读写线程数,而且须要两个条件 threading.Condition 用来处理哪方优先的通知。计数引用能够扩大语义:正数:表示正在读操做的线程数,负数:表示正在写操做的线程数(最多-1)it

在获取读操做时,先而后判断时候有等待的写线程,没有,进行读操做,有,则等待读的计数加 1 后等待 Condition 通知;等待读的计数减 1,计数引用加 1,继续读操做,若条件不成立,循环等待;io

在获取写操做时,若锁没有被占用,引用计数减 1,若被占用,等待写线程数加 1,等待写条件 Condition 的通知。

读模式和写模式的释放都是同样,须要根据判断去通知对应的 Condition:

class RWLock(object):
    def __init__(self):
        self.lock = threading.Lock()
        self.rcond = threading.Condition(self.lock)
        self.wcond = threading.Condition(self.lock)
        self.read_waiter = 0    # 等待获取读锁的线程数
        self.write_waiter = 0   # 等待获取写锁的线程数
        self.state = 0          # 正数:表示正在读操做的线程数   负数:表示正在写操做的线程数(最多-1)
        self.owners = []        # 正在操做的线程id集合
        self.write_first = True # 默认写优先,False表示读优先

    def write_acquire(self, blocking=True):
        # 获取写锁只有当
        me = threading.get_ident()
        with self.lock:
            while not self._write_acquire(me):
                if not blocking:
                    return False
                self.write_waiter += 1
                self.wcond.wait()
                self.write_waiter -= 1
        return True

    def _write_acquire(self, me):
        # 获取写锁只有当锁没人占用,或者当前线程已经占用
        if self.state == 0 or (self.state < 0 and me in self.owners):
            self.state -= 1
            self.owners.append(me)
            return True
        if self.state > 0 and me in self.owners:
            raise RuntimeError('cannot recursively wrlock a rdlocked lock')
        return False

    def read_acquire(self, blocking=True):
        me = threading.get_ident()
        with self.lock:
            while not self._read_acquire(me):
                if not blocking:
                    return False
                self.read_waiter += 1
                self.rcond.wait()
                self.read_waiter -= 1
        return True

    def _read_acquire(self, me):
        if self.state < 0:
            # 若是锁被写锁占用
            return False

        if not self.write_waiter:
            ok = True
        else:
            ok = me in self.owners
        if ok or not self.write_first:
            self.state += 1
            self.owners.append(me)
            return True
        return False

    def unlock(self):
        me = threading.get_ident()
        with self.lock:
            try:
                self.owners.remove(me)
            except ValueError:
                raise RuntimeError('cannot release un-acquired lock')

            if self.state > 0:
                self.state -= 1
            else:
                self.state += 1
            if not self.state:
                if self.write_waiter and self.write_first:   # 若是有写操做在等待(默认写优先)
                    self.wcond.notify()
                elif self.read_waiter:
                    self.rcond.notify_all()
                elif self.write_waiter:
                    self.wcond.notify()

    read_release = unlock
    write_release = unlock
相关文章
相关标签/搜索