-
-
Save ivanjx/5d8f11abb8c91fca71fb74f4888a7de1 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, int fid2) | |
{ | |
lock (m_forks) | |
{ | |
while (m_forks[fid] == 0 || m_forks[fid2] == 0); | |
m_forks[fid] = 0; | |
m_forks[fid2] = 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, 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