Python recipe(16):ReadWriteLock

代码何在?

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
'''
Created on 2010-5-28

@author: lk
'''
import threading
class ReadWriteLock:
    def __init__(self):
        self._read_ready = threading.Condition()
        self._readers = 0
        
    def acquire_read(self):
        self._read_ready.acquire()
        try:
            self._readers+=1
        finally:
            self._read_ready.release()
    
    def release_read(self):
        self._read_ready.acquire()
        try:
            self._readers-=1
            if not self._readers:
                self._read_ready.notifyAll()
        finally:
            self._read_ready.release()
            
    def acquire_write(self):
        self._read_ready.acquire()
        while self._readers:
            self._read_ready.wait()
    
    def release_write(self):
        self._read_ready.release()

if __name__ == '__main__':
    pass

以上代码改写自Python Cookbook 6-4

概述:

    不必多说,用Python实现的读写锁(ReadWriteLock):允许同时多个reader,但只能有一个writer,并且writer工作时reader也不能读

代码说明:

1.实现方法和其他语言没有太大区别,这里threading模块是python实现的高级多线程模块(相对low-level的thread模块而言)

2.python中的condition信号量对象其实还被委托了lock的一些列操作,如acquire和release等,比较方便

posted on 2010-05-28 23:13  tomsheep  阅读(886)  评论(1编辑  收藏  举报

导航