繁体   English   中英

读者/作家问题优先级

[英]The Readers/Writers Problem priority

我为 java 中的读写器问题开发了一个解决方案(有关此http 的一些信息://lass.cs.umass.edu/~shenoy/courses/fall08/lectures/Lec11.Z4370075BA41912904EED0075BA41912904EED .

但是,我不确定如何修改代码以支持作者或给予读者和作者相同的优先级。 我的代码是什么类型的问题,我如何看到它?

public class ReaderWriter{


    int numberOfReaders;
    int numberOfWriters;

    public ReaderWriter(){
        this.numberOfReaders = 0;
        this.numberOfWriters = 0;
    }

    public synchronized void requestRead(){
        while(this.numberOfWriters > 0)
            wait();

        this.numberOfReaders++;
    }

    public synchronized void releaseRead(){
        this.numberOfReaders--;
        notifyAll();
    }

    public synchronized void requestWrite(){
        while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
            wait();

        this.numberOfWriters++; 
    }

    public synchronized void releaseWrite(){
        this.numberOfWriters--;
        notifyAll();
    }
}

你的版本有利于读者(并且会使作家挨饿)。 这是一个有利于作家的修改版本(并且可能会使读者挨饿):

    int numberOfReaders;
    int numberOfWriters;
    int numberOfRequestedWriters;  // ++

    public ReaderWriter(){
        this.numberOfReaders = 0;
        this.numberOfWriters = 0;
        this.numberOfRequestedWriters = 0; // ++
    }

    public synchronized void requestRead(){
        while(this.numberOfWriters > 0  // --
              || this.numberOfRequestedWriters > 0) // ++
            wait();

        this.numberOfReaders++;
    }

    public synchronized void releaseRead(){
        this.numberOfReaders--;
        notifyAll();
    }

    public synchronized void requestWrite(){
        this.numberOfRequestedWriters++; // ++
        while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
            wait();
        this.numberOfRequestedWriters--; // ++

        this.numberOfWriters++; 
    }

    public synchronized void releaseWrite(){
        this.numberOfWriters--;
        notifyAll();
    }
}

要控制锁的分布方式,您需要维护一个等待线程队列。 除非您要保护的代码段很昂贵,否则简单的锁可能会更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM