This C# Program Illustrates Dining Philosopher Problem. Here the Dining philosopher problem is solved and the results are displayed.
Here is source code of the C# Program to Illustrate Dining Philosopher Problem. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/*
* C# Program to Illustrate Dining Philosopher Problem
*/
using System;
using System.Threading;
class philofork
{
bool[] fork = new bool[5];
public void Get(int left, int right)
{
lock (this)
{
while (fork[left] || fork[right]) Monitor.Wait(this);
fork[left] = true; fork[right] = true;
}
}
public void Put(int left, int right)
{
lock (this)
{
fork[left] = false; fork[right] = false;
Monitor.PulseAll(this);
}
}
}
class Philo
{
int n;
int thinkDelay;
int eatDelay;
int left, right;
philofork philofork;
public Philo(int n, int thinkDelay, int eatDelay, philofork philofork)
{
this.n = n;
this.thinkDelay = thinkDelay; this.eatDelay = eatDelay;
this.philofork = philofork;
left = n == 0 ? 4 : n - 1;
right = (n + 1) % 5;
new Thread(new ThreadStart(Run)).Start();
}
public void Run()
{
for (; ; )
{
try
{
Thread.Sleep(thinkDelay);
philofork.Get(left, right);
Console.WriteLine("Philosopher " + n + " is eating...");
Console.ReadLine();
Thread.Sleep(eatDelay);
philofork.Put(left, right);
}
catch
{
return;
}
}
}
}
public class philopblm
{
public static void Main()
{
philofork philofork = new philofork();
new Philo(0, 10, 50, philofork);
new Philo(1, 20, 40, philofork);
new Philo(2, 30, 30, philofork);
new Philo(3, 40, 20, philofork);
new Philo(4, 50, 10, philofork);
}
}
Here is the output of the C# Program:
Philosopher 0 is eating... Philosopher 1 is eating... Philosopher 2 is eating... Philosopher 3 is eating... Philosopher 4 is eating... Philosopher 0 is eating... Philosopher 1 is eating... Philosopher 2 is eating... Philosopher 3 is eating... Philosopher 4 is eating... Philosopher 0 is eating...
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.
Next Steps:
- Get Free Certificate of Merit in C# Programming
- Participate in C# Programming Certification Contest
- Become a Top Ranker in C# Programming
- Take C# Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Computer Science Internship
- Apply for C# Internship
- Practice MCA MCQs
- Practice Computer Science MCQs
- Buy MCA Books