---
# System prepended metadata

title: 'OS Homework 4: Dining Philosophers'
tags: [OS]

---

---
tags: OS
---

# OS Homework 4: Dining Philosophers
105042015 沈冠妤 外語20

## :memo: Code Explain

* Include libraries

![](https://i.imgur.com/YwAtbWy.png)
 
* Define states of philosophers

![](https://i.imgur.com/N4OUpcS.png)

* Declare mutex and 5 condition variables
* Declare functions to be used
* Initialize states of philosophers to THINKING

![](https://i.imgur.com/WN9LRg1.png)

### Main():

* Declare 5 threads and their indexs, indicating 5 philosophers
* Create 5 threads which executes **philosopher(&num[i])** (Explain later)
* Join threads
* destroy conditional variables and mutex

![](https://i.imgur.com/20YQoyE.png)

### philosopher():
* **i** indicates the index of the philosopher
* **period** indicates the time of sleeping
* Set the state of **i** philosopher to** THINKING**
* Generate a random sleeping time
* Sleep for **period** of time
* --
* Try to **pickup_fork()** after sleeping (Explain later)
* Generate a random eating time
* Sleep for **period** of time
* **return_fork()** (Explain later)
* Exit

![](https://i.imgur.com/VBmUzfm.png)

### pickup_fork():

* Get mutex lock
* Change the state of the philosopher to HUNGRY
* Test if left or right neighbors are eating by **test()** (Explain later)
    * If one of the neighbors is eating: wait until cv[i] is signaled
    * Else, release the mutex lock

![](https://i.imgur.com/dv3xVU8.png)

### test():

* If both neighbors are not eating, ane the philosopher himself is hungry
    * Signal cv[i] to wake up the sleeping philosopher
    * Change the state of the philosopher to EATING
    * Return 1
* Else, return 0 to keep the philospher sleeping

![](https://i.imgur.com/4S8ru9Z.png)

### return_fork():

* Get the mutex lock
* Change the state of the philosopher to THINKING
* Test if neighbors want to eat
* Release the mutex lock

![](https://i.imgur.com/xsLM8FU.png)

## :memo: Result Screenshot

![](https://i.imgur.com/VXUIC3v.png)
