-
-
Save ivanjx/7d44901c8f736e804c8cf8ecdc0049eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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