0

Im tackling the dining philosophers algorithm. I need to spawn 5 philosophers which I have done so using this code

main() ->
    philos1 = spawn (?MODULE, philosopher, []),
    philos2 = spawn (?MODULE, philosopher, []),
    philos3 = spawn (?MODULE, philosopher, []),
    philos4 = spawn (?MODULE, philosopher, []),
    philos5 = spawn (?MODULE, philosopher, []),
    fork1 = spawn (?MODULE, fork, []),
    fork2 = spawn (?MODULE, fork, []),
    fork3 = spawn (?MODULE, fork, []),
    fork4 = spawn (?MODULE, fork, []),
    fork5 = spawn (?MODULE, fork, []).

Could someone give me a rough idea of what the philosopher and fork functions would look like?

iain man
  • 7
  • 2

1 Answers1

1

From Wikipedia:

each philosopher is instructed to behave as follows:

think until the left fork is available; when it is, pick it up;
think until the right fork is available; when it is, pick it up;
when both forks are held, eat for a fixed amount of time;
then, put the right fork down;
then, put the left fork down;
repeat from the beginning.

So each philosophers needs to check if his left fork is available, if it is, mark it as unavailable, maybe by sending a message to the fork, and continue to the next stage - checking the right fork. If the fork isn't available then he need to think (sleep and then checking again).

If he manage to get the right fork he can start eating, for a fixed amount of time.

So what do we have for each philosopher?

  • Wait for left fork - a function that tries to pick up the left fork and if it manage to do so go to next stage, if not, repeat.

  • Wait for right fork - a function that tries to pick up the right fork and if it manage to do so go to next stage, if not, repeat.

  • Eat - a function that wait for a fixed amount of time and then release both of the forks and repeat.

The fork need to manage who can pick it up, so no two philosophers will ever use the same fork together. so it need to ave a free and release function.

A better way to do it might be with gen_fsm. The fork will have two states - available or unavailable, and the philosophers wil have wait_for_left_fork, wait_for_right_fork and eat.

Deddy
  • 169
  • 1
  • 13