From b5fc96ef94427658e08c401e90d5469d4e582fd3 Mon Sep 17 00:00:00 2001 From: romanschenk37 <84532681+romanschenk37@users.noreply.github.com> Date: Thu, 7 Apr 2022 13:31:57 +0200 Subject: [PATCH] Solved Task Philosopher --- .../zhaw/prog2/philosopher/ForkManager.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/code/Philosopher/src/main/java/ch/zhaw/prog2/philosopher/ForkManager.java b/code/Philosopher/src/main/java/ch/zhaw/prog2/philosopher/ForkManager.java index bbef69e..6c2fa22 100644 --- a/code/Philosopher/src/main/java/ch/zhaw/prog2/philosopher/ForkManager.java +++ b/code/Philosopher/src/main/java/ch/zhaw/prog2/philosopher/ForkManager.java @@ -16,7 +16,7 @@ class ForkManager { // maximum concurrent threads acquiring forks - used for internal statistics private static final LockFreeMax concurrentAcquires = new LockFreeMax(); - private final Lock mutex; // shared mutex for all forks + //private final Lock mutex; // shared mutex for all forks private final int delayTime; // delay in milliseconds between acquiring / releasing the forks private final int numForks; // amount of forks to be managed private final Fork[] forks; // array of managed forks @@ -27,12 +27,12 @@ class ForkManager { * @param delayTime delay in milliseconds between acquiring / releasing the forks */ public ForkManager(int numForks, int delayTime) { - this.mutex = new ReentrantLock(); + //this.mutex = new ReentrantLock(); this.delayTime = delayTime; this.numForks = numForks; this.forks = new Fork[numForks]; for (int forkId = 0; forkId < numForks; forkId++) - forks[forkId] = new Fork(forkId, mutex); + forks[forkId] = new Fork(forkId); } /** @@ -42,10 +42,15 @@ class ForkManager { * @param philosopherId id of the philosopher */ public void acquireForks(int philosopherId) throws InterruptedException { + Fork leftFork = leftFork(philosopherId); + Fork rightFork = rightFork(philosopherId); // acquire forks sequentially - leftFork(philosopherId).acquire(philosopherId); + while(!(leftFork.getState() == FREE && rightFork.getState() == FREE)){ + forkDelay(); + } + leftFork.acquire(philosopherId); forkDelay(); - rightFork(philosopherId).acquire(philosopherId); + rightFork.acquire(philosopherId); } /** @@ -136,12 +141,12 @@ class ForkManager { /** * Constructor for a fork. * @param id unique id of the fork - * @param mutex shared mutex to use for wait conditions + * //@param mutex shared mutex to use for wait conditions */ - public Fork(int id, Lock mutex) { + public Fork(int id) { this.id = id; this.ownerId = -1; - this.mutex = mutex; + this.mutex = new ReentrantLock();; this.cond = mutex.newCondition(); } @@ -195,6 +200,10 @@ class ForkManager { public String toString() { return "Fork {" + "id=" + id + ", state=" + state + ", owner=" + ownerId + '}'; } + + public ForkState getState(){ + return state; + } } /*