Skip to content

Instantly share code, notes, and snippets.

@ivanjx
Created May 14, 2021 17:17
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 ivanjx/7d44901c8f736e804c8cf8ecdc0049eb to your computer and use it in GitHub Desktop.
Save ivanjx/7d44901c8f736e804c8cf8ecdc0049eb to your computer and use it in GitHub Desktop.
using System.Threading;
int[] m_forks = new[]
{
1,
1,
1,
};
void TakeFork(int fid)
{
lock (m_forks)
{
while (m_forks[fid] == 0);
m_forks[fid] = 0;
}
}
void ReturnFork(int fid)
{
m_forks[fid] = 1;
}
void Philosopher(int id)
{
while (true)
{
Console.WriteLine("[{0}] Thinking...", id);
int secondForkId = (id + 1) % m_forks.Length;
TakeFork(id);
TakeFork(secondForkId);
Console.WriteLine("[{0}] Eating with {0} and {1}...",
id,
secondForkId);
ReturnFork(id);
ReturnFork(secondForkId);
}
}
void Main()
{
new Thread(new ThreadStart(() => Philosopher(0))).Start();
new Thread(new ThreadStart(() => Philosopher(1))).Start();
new Thread(new ThreadStart(() => Philosopher(2))).Start();
Console.ReadKey();
}
Main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment