-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulation.cs
More file actions
61 lines (52 loc) · 1.76 KB
/
Copy pathSimulation.cs
File metadata and controls
61 lines (52 loc) · 1.76 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
using System;
using System.Collections;
using System.Threading;
namespace BridgeProblem
{
class Simulation
{
private int numberOfRightCars = 2;
private int numberOfLeftCars = 3;
ArrayList waitingCars = new ArrayList();
Random rnd = new Random();
//Runs the simulation with the number of cars
public void RunSim(int rightCars, int leftCars)
{
this.numberOfRightCars = rightCars;
this.numberOfLeftCars = leftCars;
//Threads for produce cars and for manage them in the bridge
Thread producerThread = new Thread(new ThreadStart(this.CarCreatorTS));
Thread bridgeThread = new Thread(new ThreadStart(this.BridgeManagerTS));
producerThread.Start();
bridgeThread.Start();
}
//Manages the waiting cars to let them cross or wait
private void BridgeManagerTS()
{
while (true)
{
if (waitingCars.Count > 0)
{
int rndNum = rnd.Next(0, waitingCars.Count);
bool cross = Bridge.Instance.CrossCar((waitingCars[rndNum] as Car));
if (cross)
{
waitingCars.RemoveAt(rndNum);
}
}
}
}
//Constantly creates cars in a separated thread
private void CarCreatorTS()
{
CarProducer producer = new CarProducer(numberOfRightCars, numberOfLeftCars);
Car c = producer.produce();
while (c != null)
{
Console.WriteLine(c.ToString());
waitingCars.Add(c);
c = producer.produce();
}
}
}
}