-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
146 lines (124 loc) · 3.75 KB
/
Program.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Data;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
new Program().Demo();
}
private static Random _rnd = new Random();
private static List<BookReader> Readers { get; set; }
public void Demo()
{
var tradingCount = 100;
var tradingsForExperiment = new Thread[tradingCount];
#region setup book readers
var initialBooks = new List<Book>() { new Book { Name = "Book 1" }, new Book { Name = "Book 2" }, new Book { Name = "Book 1" } };
Readers = new BookReader[10].Select((r, i) => new BookReader(i, initialBooks)).ToList();
#endregion
for (var i = 0; i < tradingsForExperiment.Length; i++)
{
tradingsForExperiment[i] = new Thread(TradeBooks);
tradingsForExperiment[i].Start();
}
for (var i = 0; i < tradingsForExperiment.Length; i++)
{
tradingsForExperiment[i].Join();
}
}
public static void TradeBooks()
{
#region pick random readers
var firstReaderIndex = _rnd.Next(0, Readers.Count - 1);
var secondReaderIndex = _rnd.Next(0, Readers.Count - 1);
while (secondReaderIndex == firstReaderIndex)
{
secondReaderIndex = _rnd.Next(0, Readers.Count - 1);
}
#endregion
Readers[firstReaderIndex].ExchangeBook(Readers[secondReaderIndex]);
}
}
class BookReader
{
public Mutex _lock = new Mutex();
public readonly int Id;
private List<Book> _books = new List<Book>();
public BookReader(int id, List<Book> initialBooks)
{
Id = id;
_books = initialBooks;
}
public void ReceiveBook(Book book)
{
try
{
if (_lock.WaitOne())
{
_books.Add(book);
}
}
finally
{
_lock.ReleaseMutex();
}
}
public void TakeBook(Book book)
{
try
{
if (_lock.WaitOne())
{
_books.Remove(book);
}
}
finally
{
_lock.ReleaseMutex();
}
}
public Book GetBook()
{
try{
if (_lock.WaitOne())
{
return _books.First();
}
}
finally
{
_lock.ReleaseMutex();
}
return null;
}
public int GetBookCount()
{
return _books.Count;
}
public void ExchangeBook(BookReader otherReader)
{
Mutex[] locks = new Mutex[] {_lock, otherReader._lock};
if (WaitHandle.WaitAll(locks))
{
var book = otherReader.GetBook();
if (book != null)
{
ReceiveBook(book);
otherReader.TakeBook(book);
Console.WriteLine("Reader {0} -> {1} gave book {2}", otherReader.Id, Id, book.Name);
}
}
foreach (var lockedMutex in locks)
{
lockedMutex.ReleaseMutex();
}
}
}
}