Skip to content

Instantly share code, notes, and snippets.

@runewake2
Created December 23, 2016 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runewake2/4a51270f72484e64f3789fb36a74f2da to your computer and use it in GitHub Desktop.
Save runewake2/4a51270f72484e64f3789fb36a74f2da to your computer and use it in GitHub Desktop.
Solution to the Dining Philosophers problem - Solves the deadlock problem by alternating the order the philosophers select their chopsticks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DiningPhilosophers
{
class Program
{
static int philisopherNumber = 5;
static Task[] philosiphers;
static SemaphoreSlim[] chopsticks;
static void Main(string[] args)
{
philosiphers = new Task[philisopherNumber];
chopsticks = new SemaphoreSlim[philisopherNumber];
for (int i = 0; i < philisopherNumber; ++i)
{
philosiphers[i] = GenerateNewPhilosopher(i);
chopsticks[i] = new SemaphoreSlim(1);
}
Task.WaitAll(philosiphers);
Console.WriteLine("Finished eating. HUZZAH!");
Console.ReadLine();
}
private static Task GenerateNewPhilosopher(int philosipherIndex)
{
return Task.Run(() =>
{
for (int i = 0; i < 100; ++i)
{
Console.WriteLine($"Phil {philosipherIndex}: Attempting to get food");
var chopstick1 = GetChopstickIndex(philosipherIndex);
var chopstick2 = GetChopstickIndex(philosipherIndex + 1);
var chopsticksList = new List<int>() { chopstick1, chopstick2 }.OrderBy(index => index).ToList();
foreach (var chopstickIndex in chopsticksList)
{
chopsticks[chopstickIndex].Wait();
}
Console.WriteLine($"Phil {philosipherIndex}: Eating");
Task.Delay(100); // NOM NOM NOM
chopsticks[GetChopstickIndex(philosipherIndex)].Release();
chopsticks[GetChopstickIndex(philosipherIndex + 1)].Release();
}
});
}
private static int GetChopstickIndex(int index)
{
return index % philisopherNumber;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment