Docsity

Dining Philosophers Servers in Concurrent Programming | CS 361, Study notes of Computer Science

Toggle sidebar
bg1
1
page 1
CS 361 Concurrent programming
Drexel University
Fall 2004
Lecture 13
©Bruce Cha and Vera Zaychikr. All rights reserved by the author.
Permission is given to students enrolled in CS361 Fall 2004to
reproduce these notes for their own use.
page 2
The dining philosophers problem
• The dining philosophers problem involves five
philosophers sitting at a round table with five forks
interleaved between them. A bowl of spaghetti sits in the
center of the table. Philosophers think for a while, become
hungry, and try to eat. After eating for a while, a
philosopher is ready to think again and the cycle repeats.
A philosopher needs both forks to eat, the one on its right
and the on its left. Sometimes the problem is presented
with chopsticks instead of forks to emphasize that a
philosopher needs both at the same time to eat. Only one
philosopher can use a fork at a time.
page 3
Constraints on the dining
philosophers
• Avoid: deadlock (each philosopher holding a fork
and refusing to relinquish it). Also, starvation
(literally). Also, favoritism.
• Desirable goal: attain maximal parallelism (a
hungry philosopher eats if its forks are not being
used by other philosophers to eat).
• Although it looks contrived, it exemplifies a
typical kind of synchronization problem, where
there are overlapping sets of resources whose use
must be coordinated.
page 4
Dining philosophers: one
solution using semaphores
• Central server object that records states of
philosophers.
• Avoids deadlock/livelock, but doesn’t
address the issue of starvation by a
philosopher
page 5
Approach taken by solution
• A philosopher thinks for a random period of time,
then becomes hungry.
• The philosopher then asks the central server for its
forks.
• The central server checks the availability of the
forks by examining the states of the hungry
philosopher’s two neighbors.
• If neither neighbor is eating, the hungry
philosopher eats. Otherwise he waits, through
P(self[i]). (One semaphore per philosopher.)
page 6
Solution, cont.
• Once a philosopher obtains its two forks, it eats
for a random amount of time, put down the forks,
and then repeats the cycle.
• When a philosopher puts down his forks, the
central server checks the philosopher’s two
neighbors with calls to the test method to see if
either is hungry.
• If either is hungry and its two forks are available,
the neighbor is unblocked with V(self[k]).
pf3
pf4
pf5

Partial preview of the text

Download Dining Philosophers Servers in Concurrent Programming | CS 361 and more Study notes Computer Science in PDF only on Docsity!

page 1

CS 361 Concurrent programming

Drexel University

Fall 2004

Lecture 13

©Bruce Cha and Vera Zaychikr. All rights reserved by the author.

Permission is given to students enrolled in CS361 Fall 2004 to

reproduce these notes for their own use.

page 2

The dining philosophers problem

  • The dining philosophers problem involves five

philosophers sitting at a round table with five forks

interleaved between them. A bowl of spaghetti sits in the

center of the table. Philosophers think for a while, become

hungry, and try to eat. After eating for a while, a

philosopher is ready to think again and the cycle repeats.

A philosopher needs both forks to eat, the one on its right

and the on its left. Sometimes the problem is presented

with chopsticks instead of forks to emphasize that a

philosopher needs both at the same time to eat. Only one

philosopher can use a fork at a time.

page 3

Constraints on the dining

philosophers

• Avoid: deadlock (each philosopher holding a fork

and refusing to relinquish it). Also, starvation

(literally). Also, favoritism.

• Desirable goal: attain maximal parallelism (a

hungry philosopher eats if its forks are not being

used by other philosophers to eat).

• Although it looks contrived, it exemplifies a

typical kind of synchronization problem, where

there are overlapping sets of resources whose use

must be coordinated.

page 4

Dining philosophers: one

solution using semaphores

• Central server object that records states of

philosophers.

• Avoids deadlock/livelock, but doesn’t

address the issue of starvation by a

philosopher

page 5

Approach taken by solution

• A philosopher thinks for a random period of time,

then becomes hungry.

• The philosopher then asks the central server for its

forks.

• The central server checks the availability of the

forks by examining the states of the hungry

philosopher’s two neighbors.

• If neither neighbor is eating, the hungry

philosopher eats. Otherwise he waits, through

P(self[i]). (One semaphore per philosopher.)

page 6

Solution, cont.

• Once a philosopher obtains its two forks, it eats

for a random amount of time, put down the forks,

and then repeats the cycle.

• When a philosopher puts down his forks, the

central server checks the philosopher’s two

neighbors with calls to the test method to see if

either is hungry.

• If either is hungry and its two forks are available,

the neighbor is unblocked with V(self[k]).

page 7

Dining philosophers server

import Utilities.; import Synchronization.;

class DiningServer extends MyObject {

private static final int // States THINKING = 0, HUNGRY = 1, EATING = 2; private int numPhils = 0; private int[] state = null; private BinarySemaphore[] self = null; // array of sem. private BinarySemaphore mutex = null;

public DiningServer(int numPhils) { super("DiningServer for " + numPhils + " philosophers"); this.numPhils = numPhils; state = new int[numPhils]; for (int i = 0; i < numPhils; i++) state[i] = THINKING; self = new BinarySemaphore[numPhils]; for (int i = 0; i < numPhils; i++) self[i] = new BinarySemaphore(0); mutex = new BinarySemaphore(1); } page 8

Dining philosophers server, cont.

private final int left(int i) { return (numPhils + i - 1)

% numPhils; } // wraparound indexing

private final int right(int i) { return (i + 1) %

numPhils; }

public void takeForks(int i) { // when want to eat

P(mutex);

state[i] = HUNGRY;

test(i); // will do a V(self[i]) if okay to eat

V(mutex);

P(self[i]);

public void putForks(int i) { // when done eating

P(mutex);

state[i] = THINKING;

test(left(i)); // may do release -- V -- for left

test(right(i)); // may do V for right

V(mutex);

page 9

Dining philosophers server, cont.

private void test(int k) {

if (state[left(k)] != EATING && state[right(k)] !=

EATING

&& state[k] == HUNGRY) {

state[k] = EATING;

V(self[k]);

page 10

Dining philosophers sample

output

/* ............... Example compile and run(s) D:>javac dphi.java dpdr.java D:>java DiningPhilosophers -R10 4 1 4 1 4 1 4 1 4 1 DiningPhilosophers: numPhilosophers=5, runTime= Philosopher 0 is alive, napThink=4000, napEat= Philosopher 1 is alive, napThink=4000, napEat= Philosopher 2 is alive, napThink=4000, napEat= Philosopher 3 is alive, napThink=4000, napEat= Philosopher 4 is alive, napThink=4000, napEat= All Philosopher threads started age()=110, Philosopher 0 is thinking for 3816 ms age()=110, Philosopher 1 is thinking for 2079 ms age()=110, Philosopher 2 is thinking for 2646 ms age()=170, Philosopher 3 is thinking for 560 ms age()=170, Philosopher 4 is thinking for 761 ms age()=720, Philosopher 3 wants to eat age()=720, Philosopher 3 is eating for 717 ms age()=940, Philosopher 4 wants to eat age()=1430, Philosopher 3 is thinking for 1653 ms age()=1430, Philosopher 4 is eating for 913 ms age()=2200, Philosopher 1 wants to eat age()=2200, Philosopher 1 is eating for 86 ms age()=2310, Philosopher 1 is thinking for 1797 ms age()=2370, Philosopher 4 is thinking for 3052 ms age()=2810, Philosopher 2 wants to eat age()=2810, Philosopher 2 is eating for 442 ms age()=3140, Philosopher 3 wants to eat age()=3300, Philosopher 2 is thinking for 3003 ms age()=3300, Philosopher 3 is eating for 465 ms age()=3740, Philosopher 3 is thinking for 1381 ms age()=3960, Philosopher 0 wants to eat

age()=3960, Philosopher 0 is eating for 247 ms age()=4120, Philosopher 1 wants to eat age()=4180, Philosopher 0 is thinking for 1642 ms age()=4180, Philosopher 1 is eating for 787 ms age()=5000, Philosopher 1 is thinking for 2828 ms age()=5170, Philosopher 3 wants to eat age()=5170, Philosopher 3 is eating for 559 ms age()=5440, Philosopher 4 wants to eat age()=5720, Philosopher 3 is thinking for 319 ms age()=5720, Philosopher 4 is eating for 850 ms age()=5830, Philosopher 0 wants to eat age()=6050, Philosopher 3 wants to eat age()=6270, Philosopher 2 wants to eat age()=6270, Philosopher 2 is eating for 33 ms age()=6320, Philosopher 2 is thinking for 92 ms age()=6430, Philosopher 2 wants to eat age()=6430, Philosopher 2 is eating for 612 ms age()=6600, Philosopher 4 is thinking for 3242 ms age()=6600, Philosopher 0 is eating for 320 ms age()=6930, Philosopher 0 is thinking for 3193 ms age()=7040, Philosopher 2 is thinking for 3221 ms age()=7040, Philosopher 3 is eating for 142 ms age()=7200, Philosopher 3 is thinking for 2902 ms age()=7800, Philosopher 1 wants to eat age()=7800, Philosopher 1 is eating for 553 ms age()=8410, Philosopher 1 is thinking for 3382 ms age()=9840, Philosopher 4 wants to eat age()=9840, Philosopher 4 is eating for 678 ms age()=10110, Philosopher 3 wants to eat age()=10110, Philosopher 0 wants to eat age()=10110, time to stop the Philosophers and exit ... end of example run(s) */

page 11

Philosopher class

import Utilities.*;

class Philosopher extends MyObject implements Runnable {

private int id = 0; private int napThink = 0; // both are in private int napEat = 0; // milliseconds private DiningServer ds = null;

public Philosopher(String name, int id, int napThink, int napEat, DiningServer ds) { super(name + " " + id); this.id = id; this.napThink = napThink; this.napEat = napEat; this.ds = ds; System.out.println(getName() + " is alive, napThink="

  • napThink + ", napEat=" + napEat); new Thread(this).start(); // self-starting object } page 12

Philosopher class, con’t

private void think() {

int napping;

napping = 1 + (int) random(napThink);

System.out.println("age()=" + age() + ", " +

getName()

+ " is thinking for " + napping + " ms");

nap(napping);

private void eat() {

int napping;

napping = 1 + (int) random(napEat);

System.out.println("age()=" + age() + ", " +

getName()

+ " is eating for " + napping + " ms");

nap(napping);

page 19

Notes on Stalling’s solution

• Prevents starvation because a philosopher

picks up a left fork and doesn’t put it down

until it eats.

• Prevents deadlock because only N-

philosophers are allowed to pick up forks

(the use of the “room” counting

semaphore), which prevents deadlock.

page 20

Maximal parallelism

– The problem with Stalling’s solution is that it

doesn’t allow maximal parallelism – one person

is eating, the rest are all blocked waiting for

their other fork. Increased parallelism if “every

other philosopher” eating instead of just one.

– There’s another solution where one philosopher

is designated as “odd” and picks up the forks in

reverse order from the others. Then deadlock

cannot occur but again maximal parallelism

isn’t achieved.

page 21

Another non-maximal solution

public void takeForks(int i) {

state[i] = HUNGRY;

if (i > 0) { P(fork[i]); P(fork[right(i)]); }

else { P(fork[right(i)]); P(fork[i]); }

state[i] = EATING;

“Odd philosopher out” takes the fork in his/her other hand. Still

doesn’t achieve maximal parallelism.

page 22

Avoiding starvation

• This solution avoids deadlock but doesn’t

guarantee that no philosopher will starve.

page 23

Exercise: avoid starvation

• Modify the program so that it is starvation-free.

One way to do this is to add another state

“starving” and not let a hungry philosopher eat if

it has a “starving” neighbor.

• A hungry philosopher enters this state if its

neighbors have put down their forks and the

philosopher under consideration has not been able

to eat.

page 24

Exercise: avoid starvation

• You must change the state of a philosopher only

when one of its neighbors puts down its forks.

Don’t make a philosopher starve the first time it

tries to pick up its forks and it can’t.

• Can’t have two neighboring philosophers starving

at the same time because either they will deadlock

or you will still have starvation.

page 25

Exercise: avoid starvation

(alternatives)

• Or you can count the number of times it has

not been able to pick up its forks, or base it

on how many times each fork has been

picked up.

• Or assign ticket numbers like Lamport’s

algorithm.

page 26

Database reader/writer problem

  • The readers and writers problem: readers may read a

database simultaneously as long as no writer writes

  • Only one writer at a time may write (if there are no active

readers).

  • Attain: maximal parallelism (readers may read

simultaneously if there is no writing), data integrity (only

one writer at a time if no readers are reading).

  • Possible additional goal: avoid writer starvation (locked

out of writing because readers are always coming along to

read).

page 27

Database reader/writer solution

import Utilities.; import Synchronization.;

class Database extends MyObject {

private int numReaders = 0; private BinarySemaphore mutex = new BinarySemaphore(1); private BinarySemaphore ok = new BinarySemaphore(1);

public Database() { super("Database"); }

page 28

Reader code

public void startRead(int i) {

P(mutex);

numReaders++;

if (numReaders == 1) {

System.out.println("age=" + age() + " reader " + i

+ " waiting to read, numReaders=" + numReaders);

P(ok);

System.out.println(" age=" + age() + " reader " + i

+ " has begun reading, numReaders=" + numReaders);

V(mutex);

public void endRead(int i) {

P(mutex);

numReaders--;

System.out.println(" age=" + age() + " reader " + i

+ " finished reading, numReaders=" + numReaders);

if (numReaders == 0) V(ok);

V(mutex);

page 29

Writer code

public void startWrite(int i) {

P(ok);

System.out.println(" age=" + age() + " WRITER " + i

+ " has begun Writing");

public void endWrite(int i) {

System.out.println(" age=" + age() + " WRITER " + i

+ " has finished Writing");

V(ok);

page 30

Notes on reader/writer solution

– Only the first reader should lock the “ok” lock.

The last reader should unlock it when it finishes

its read. Then the

– Writers can write. Starvation of writers might

occur.