python 读写锁学习及实践

读写锁:

允许多个对象同时读,只允许一个写。写的时候不能有读锁。

import threading
from time import sleep 

class Item:
    def __init__(self, x):
        self.x = x
    
    def add(self):
        self.x += 1

x = Item(100)

class RWLock:
    def __init__(self):
        self.lock = threading.Lock()
        self.cnt = 0
        self.extra = threading.Lock()

    def read_acquire(self):
        with self.extra:
            self.cnt += 1
            if self.cnt == 1:
                self.lock.acquire()

    def read_release(self):
        with self.extra:
            self.cnt -= 1
            if self.cnt == 0:
                self.lock.release()

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

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

Lock = RWLock()

class MyThread:
    def __init__(self, flag):
        self._thread = None
        self.flag = flag

    def observe(self, x):
        thread_name = self._thread.getName()
        while True:
            print('{} ready to acquire the read lock'.format(thread_name))
            Lock.read_acquire()
            print('{} acquired the read lock'.format(thread_name))
            print('{} ready to read x'.format(thread_name))
            print(x.x)
            print('{} read x done'.format(thread_name))
            print('{} ready to release the read lock'.format(thread_name))
            Lock.read_release()
            print('{} released the read lock'.format(thread_name))
            print('{} sleeping 5s......'.format(thread_name))
            sleep(5)

    def modify(self, x):
        thread_name = self._thread.getName()
        print('{} ready to acquire the lock'.format(thread_name))
        Lock.write_acquire()
        print('{} acquired the lock'.format(thread_name))
        print('{} ready to write x'.format(thread_name))
        x.add()
        print('{} write x done'.format(thread_name))
        print('{} ready to release the write lock'.format(thread_name))
        Lock.write_release()
        print('{} released the write lock'.format(thread_name))

    def start(self, x):
        if self.flag:
            self._thread = threading.Thread(target=self.observe, args=(x,))
        else:
            self._thread = threading.Thread(target=self.modify, args=(x,))
        self._thread.start()


if __name__ == '__main__':
    a = MyThread(True)
    b = MyThread(True)
    c = MyThread(False)
    
    a.start(x)
    c.start(x)
    b.start(x)

需要指出的是这个实现是读优先的。

参考资料:

用Python实现读写锁

原文地址:https://www.cnblogs.com/LuoboLiam/p/15338632.html