Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Task2;
- public class SolutionWithNoSynchronization implements MemoryWrapper{
- private MemorySegment _memory = null;
- private boolean writing = false;
- private int readers = 0, writers = 0;
- public SolutionWithNoSynchronization(){
- _memory = new MemorySegment();
- }
- public void read(Process p){
- p.setState("wantread");
- beforeRead();
- p.setState("reading");
- _memory.read();
- p.setState("idle");
- afterRead();
- }
- public void write(Process p){
- p.setState("wantwrite");
- beforeWrite();
- p.setState("writing");
- _memory.write();
- p.setState("idle");
- afterWrite();
- }
- private synchronized void beforeRead() {
- while(!okToRead()) {
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- readers++;
- }
- private synchronized void afterRead() {
- readers--;
- notifyAll();
- }
- private synchronized void beforeWrite() {
- while(!okToWrite()) {
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- writing = true;
- }
- private synchronized void afterWrite() {
- writing = false;
- notifyAll();
- }
- private boolean okToRead() {
- return !writing;
- }
- private boolean okToWrite() {
- return !writing && readers == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement