-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBridge.cs
More file actions
70 lines (61 loc) · 2.13 KB
/
Copy pathBridge.cs
File metadata and controls
70 lines (61 loc) · 2.13 KB
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
using System.Threading;
namespace BridgeProblem
{
//Represents the bridge and executes the cross request in a synchronized block to avoid concurrency issues
public class Bridge
{
Car.Direction currentDirection; //Direction of the current car in the bridge
int carsInBridge = 0; //The number of cars crossing the bridg at once in the same direction
//Singleton Setup
private static Bridge instance;
private Bridge() { }
public static Bridge Instance
{
get
{
if (instance == null)
{
instance = new Bridge();
}
return instance;
}
}
//If the car is allowed to cross it start a new Thread to execute the crossing
public bool CrossCar(Car c)
{
lock (this) //Synchronized block
{
//If the bridge is empty
if (carsInBridge == 0)
{
new Thread(new ThreadStart(c.Cross)).Start();
carsInBridge++;
currentDirection = c.GetDirection();
return true;
}
//If a car is currently crossing the bridge in the same direction, the c car is started
if (carsInBridge != 0 && c.GetDirection() == currentDirection)
{
new Thread(new ThreadStart(c.Cross)).Start();
carsInBridge++;
currentDirection = c.GetDirection();
return true;
}
//If the car in the bridge has a different direction the c car is not allowed to cross
if (carsInBridge > 0 && c.GetDirection() != currentDirection)
{
return false;
}
return false;
}
}
//To remove the car once it reaches the otherside
public void CarReachedEnd()
{
lock (this)
{
carsInBridge--;
}
}
}
}