-
Notifications
You must be signed in to change notification settings - Fork 1
/
DiningPhilosophers.cs
52 lines (50 loc) · 1.72 KB
/
DiningPhilosophers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency
{
#pragma warning disable CA1001 // Types that own disposable fields should be disposable
public class DiningPhilosophers
#pragma warning restore CA1001 // Types that own disposable fields should be disposable
{
private readonly Semaphore fork0 = new Semaphore(1,1);
private readonly Semaphore fork1 = new Semaphore(1, 1);
private readonly Semaphore fork2 = new Semaphore(1, 1);
private readonly Semaphore fork3 = new Semaphore(1, 1);
private readonly Semaphore fork4 = new Semaphore(1, 1);
public void Dine(int philosopher)
{
switch (philosopher)
{
case 0:
fork0.WaitOne();
fork4.WaitOne();
fork4.Release();
fork0.Release();
break;
case 1:
fork0.WaitOne();
fork1.WaitOne();
fork1.Release();
fork0.Release();
break;
case 2:
fork1.WaitOne();
fork2.WaitOne();
fork2.Release();
fork1.Release();
break;
case 3:
fork2.WaitOne();
fork3.WaitOne();
fork3.Release();
fork2.Release();
break;
case 4:
fork3.WaitOne();
fork4.WaitOne();
fork4.Release();
fork3.Release();
break;
}
}
}
}