Skip to content

RWLock并未达到写优先的效果,实现中有个小BUG #1

@Alien-Leon

Description

@Alien-Leon

你好,代码的实现并未达到写优先的效果,对应的测试代码为:

class TestObj:
    def __init__(self, x):
        self.x = x

def read_data(obj, lock):
    while True:
        with lock.read():
            print(threading.current_thread().name, 'read data', obj.x)
            time.sleep(random.random())

def write_data(obj, lock):
    while True:
        start = datetime.datetime.now()
        print('writer waiting...')
        with lock.write():
            print('write data', obj.x, 'waiting', datetime.datetime.now() - start)
            time.sleep(2)
        time.sleep(2)

if __name__ == '__main__':
    rwlock = RWLockWrite()
    # rwlock = RWlock()
    obj = TestObj(1)
    for i in range(10):
        threading.Thread(target=read_data, args=(obj, rwlock), name='reader %d' % i).start()

    threading.Thread(target=write_data, args=(obj, rwlock), name='writer 1').start()

BUG原因在于write_acquire函数
函数中的顺序应当是这样:

    def write_acquire(self):
        """Acquire a write lock. Blocks until there are no acquired read- or write-locks."""
        self._mutex_.acquire()
        self._write_locked_ = True    # 提前声明进入写状态
        while self._readers_ > 0:
            self._write_allowed_condition_.wait()
        self._mutex_.release()

原因是原来的顺序会让Writer一直等待 self._readers_==0,但是在Reader一直占用的情况下,Writer会不断等待,无法达到Writer优先的效果。

在这样的修改中可以在一个Writer的情况下达成Writer优先的效果,多Writer的情况估计还是得修改一下。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions