# Philosopher dinner - Solution 1

##

## Solution 1

### State Diagram

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2FBOhniRraykbac7wSgOex%2Fa.png?alt=media&#x26;token=c3c0e8cf-dde0-4fda-bc15-aef5af0ba334" alt=""><figcaption></figcaption></figure>

This is a possible solution for the dining-philosopher problem.

* when a philosopher gets hungry, he/she first gets the left fork and then holds it while waits for the right one.

Let’s look at the implementation of this solution!

## Code

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2FdcBogAOiyUNXejSNbXvv%2Fa.png?alt=media&#x26;token=68d37b9f-c7a2-4f38-86c2-8591d0b0e615" alt=""><figcaption></figcaption></figure>

## Deadlock conditions

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2F3KD9I6lelUsyoNi0G3Nk%2Fa.png?alt=media&#x26;token=2714f5cf-40bb-452a-8697-0c513cea6664" alt=""><figcaption></figcaption></figure>

This solution works some times, but can suffer from deadlock.

Let’s identify the four necessary conditions.

* **mutual exclusion** – the forks are not sharable at the same time.
* **hold and wait** – each philosopher, while waiting to acquire the right fork, holds the left one.
* **no preemption** – only the philosophers can release the fork(s) in their possession.
* **circular wait** – if all philosophers acquire the left fork, there is a chain in which every philosopher waits for a fork in possession of another philosopher.
