Skip to content

Instantly share code, notes, and snippets.

@MeinLiX
Last active June 7, 2021 10:29
Show Gist options
  • Save MeinLiX/776d9a422426b407c4a23a5e3b9604ae to your computer and use it in GitHub Desktop.
Save MeinLiX/776d9a422426b407c4a23a5e3b9604ae to your computer and use it in GitHub Desktop.
Dining philosophers problem C#
using System;
using System.Collections.Generic;
using System.Threading;
namespace Project
{
class Program
{
private static List<Fork> fork = new ();
private static List<Philosopher> ph = new ();
private static List<Thread> th = new ();
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
fork.Add(new Fork());
ph.Add(new Philosopher((i + 1).ToString(), i));
th.Add(new(ph[i].Start));
}
foreach(var t in th)
t.Start(fork);
}
}
enum PhiState
{
isHunger,
isNotHunger,
}
public class Philosopher
{
private readonly string philosopherName;
private readonly int number;
private PhiState state = PhiState.isNotHunger;
private int count = 0;
public Philosopher(string Name, int number)
{
philosopherName = Name;
this.number = number;
}
public void Start(object obj)
{
while (true)
{
Thread.Sleep(new Random().Next(1000, 5000));
ChangeStatus();
if (state == PhiState.isHunger)
GetFork((List<Fork>)obj);
}
}
private void GetFork(List<Fork> fork)
{
Console.WriteLine($"Philosopher {philosopherName} waiting forks");
Monitor.Enter(fork);
try
{
int first = number;
int second = (number + 1)% fork.Count;
if (!fork[first].IsUsing && !fork[second].IsUsing)
{
Console.WriteLine($"Philosopher {philosopherName} getting forks.");
fork[first].IsUsing = true;
fork[second].IsUsing = true;
count++;
Console.WriteLine($"Philosopher {philosopherName} eating ({count}).");
Console.WriteLine($"Forks with numbers {first + 1} and {second + 1} are using.");
Thread.Sleep(250);
fork[first].IsUsing = false;
fork[second].IsUsing = false;
}
}
finally
{
Monitor.Exit(fork);
}
}
private void ChangeStatus()
{
state = (state == PhiState.isHunger) ? PhiState.isNotHunger:PhiState.isHunger;
if (state == PhiState.isNotHunger)
Console.WriteLine("Philosopher {0} thinking.", philosopherName);
}
}
public class Fork
{
private bool isUsing = false;
public bool IsUsing
{
get { return isUsing; }
set { isUsing = value; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment