-
Notifications
You must be signed in to change notification settings - Fork 0
/
Programmer.cs
60 lines (53 loc) · 1.83 KB
/
Programmer.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
using System;
using ConcurrencyUtilities;
using Thread = System.Threading.Thread;
using TestConcurrencyUtilities;
namespace RiverCrossing
{
public class Programmer
{
Barrier _groupBarrier; // Size: 2
Semaphore _boardPermission; // Size: 2
Semaphore _partnerCanBoard; // Size: 1...
Barrier _boatBarrier; // Size: 4
Semaphore _groupPairer;
bool _isLinux;
string _bgColour;
public Programmer(bool isLinux, Semaphore groupPairer, Barrier groupBarrier, Semaphore boardPermission,
Semaphore partnerCanBoard, Barrier boatBarrier) {
_isLinux = isLinux;
_groupPairer = groupPairer;
_groupBarrier = groupBarrier;
_boardPermission = boardPermission;
_partnerCanBoard = partnerCanBoard;
_boatBarrier = boatBarrier;
_bgColour = _isLinux ? "{!red}" : "{!cyan}";
}
public void Run() {
TestSupport.DebugThread("{black}Started");
// Attempt to board the boat:
// Pair up and decide the captain
_groupPairer.Acquire();
// Wait for pair to arrive
if (_groupBarrier.Arrive()) { // If we were selected to be the captain
_boardPermission.Acquire(); // Get permission to let our group onto the boat (reserve space for a pair)
TestSupport.DebugThread(_bgColour + "{black}Board*");
_partnerCanBoard.Release(); // Allow the non-captain of our pair to board
// TestSupport.SleepThread(1000);
} else {
_partnerCanBoard.Acquire(); // Wait for the captain to allow us to board
TestSupport.DebugThread(_bgColour + "{black}Board");
}
_groupPairer.Release();
// TestSupport.DebugThread("{!green}{black}Board");
// Board the boat
if (_boatBarrier.Arrive()) {
Row();
_boardPermission.Release(2); // Free space on the boat for two pairs
}
}
void Row() {
TestSupport.DebugThread("{!green}{black}Row{reset}\n" + new String('-', 144));
}
}
}