Lab 4 - Dining Philosophers

A very common concurrency problem which occurs is that of the Dining Philosophers. In this problem, there are 5 philosophers sitting at a circular table. In the center of the table is food. There are a total a five forks, one on both the right and left of each philosopher. Since there are only five forks, the philosophers must share their forks with the philosopher on each side of them. In order to eat, a philosopher must have both the left fork and the right fork. The purpose of this problem is to design a way to take forks such that no philosopher starves. Assume that when a philosopher gets done eating and returns the forks, he is still hungry and will continue to try to get the forks.

A common incorrect solution is given below:

GetForks()
	Take Left Fork
	Take Right Fork
	Eat
	Return Left Fork
	Return Right Fork

The problem with this solution occurs when each of the philosophers grabs their left fork at the same time. At this point, everyone is waiting for the right fork. However, none of the philosophers will put a fork down and therefore they will never get to eat. This situation is called deadlock and is the result of circular waiting.

In order to implement this problem, you will need to use binary semaphores. Use one semaphore for each fork. Taking a fork can be implemented with the semTake() function, and returning a fork can be implemented with a semGive() function.

In this lab, you will need to:

1. Create a new project in Tornado.
2. Download the source file source.cpp and insert it into the project.
3. Modify the progStart function to spawn 5 tasks, one for each philosopher.
4. Implement the GetForks function(s). After acquiring both forks, print the number of the philosopher that is currently eating. Hint: The solution will be made easier if you write more than one GetForks function.
5. Add any other necessary code which your project requires (i.e. run states, additional functions, etc.).
6. Explain in the lab report why your solution is correct. Also identify the critical region, and explain how the circular wait for semaphores can cause deadlock.