如何测试自己写的读写锁是正确的呢?
澳门新葡京
澳门新葡京
当前位置 : 澳门新葡京 > 澳门新葡京网址

如何测试自己写的读写锁是正确的呢?

用Python写的读写锁,用什么例子才能够测试是正确的还是错误的呢?

#!/usr/bin/python2.7
#coding:utf-8

Created on 2016年8月19日

@author: litten

from threading import Lock
from threading import Thread
class ReaderLockobject:
    
    读操作时不能够写,所以读的时候需要获得写锁。
    当self.__r_cnt不为0时,不需要获得写锁,因为此时有线程获得写锁。 
    self.__r_cnt需要互斥访问,所以需要一个锁self.__r_mutex
    
    def __init__self, writer_lock:
        self.__writer_lock = writer_lock
        self.__r_mutex = Lock
        self.__r_cnt = 0
        
    def acquireself:
        
        如果self.__r_cnt不为0,则不需要获得写锁
        
        self.__r_mutex.acquire
        if self.__r_cnt == 0:
            self.__writer_lock.acquire
        self.__r_cnt += 1
        self.__r_mutex.release
        #something operation
        
    def releaseself:
        
        当self.__r_cnt为0时,才需要释放写锁
        
        self.__r_mutex.acquire
        self.__r_cnt -= 1
        if self.__r_cnt == 0:
            self.__writer_lock.release
        self.__r_mutex.release
        
class WriterLockobject:
    def __init__self:
        self.__w_mutex = Lock
        
    def acquireself:
        self.__w_mutex.acquire
        
    def releaseself:
        self.__w_mutex.release
        
        
file = []
class ReaderThread:
    def __init__self, reader_lock:
        Thread.__init__self
        self.__reader_lock = reader_lock
    def runself:
        self.read
    def readself:
        self.__reader_lock.acquire
        s = %s is read, file len is %s % self.getName, lenfile
        print s
        self.__reader_lock.release
        
class WriterThread:
    def __init__self, writer_lock:
        Thread.__init__self
        self.__writer_lock = writer_lock
        
    def runself:
        self.write
    def writeself:
        self.__writer_lock.acquire
        s = %s is write % self.getName
        file.appendfile
        print s
        self.__writer_lock.release
if __name__ == __main__:
    writer_lock = WriterLock
    reader_lock = ReaderLockwriter_lock
    print ---start---
    readers = []
    writers = []
    for i in xrange10:
        reader = Readerreader_lock
        reader.start
        readers.appendreader
        writer = Writerwriter_lock
        writer.start
        writers.appendwriter
        
    for i in xrange10:
        readers[i].join
        writers[i].join
    
    print ---end---

栏目列表

广告位

澳门新葡京