---
tags: OS
---
# OS Homework 4: Dining Philosophers
105042015 沈冠妤 外語20
## :memo: Code Explain
* Include libraries

* Define states of philosophers

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

### 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

### 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

### 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

### 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

### return_fork():
* Get the mutex lock
* Change the state of the philosopher to THINKING
* Test if neighbors want to eat
* Release the mutex lock

## :memo: Result Screenshot
