Skip to content

Commit

Permalink
fix race condition CarCount
Browse files Browse the repository at this point in the history
  • Loading branch information
Grimmgockel committed May 23, 2023
1 parent 6312bde commit 899b698
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 30 deletions.
6 changes: 6 additions & 0 deletions src/Solution1/ConsoleApp1/ConsoleApp1.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,10 @@
</None>
</ItemGroup>

<ItemGroup>
<Compile Remove="clients\ParkerClientDeprecatedDeprecated.cs" />
<Compile Remove="clients\CruiserClientDeprecatedDeprecated.cs" />
<Compile Remove="clients\CarClientDeprecated.cs" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Solution1/ConsoleApp1/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
var cruisers = await Task.WhenAll(cruiserClients);

var parkerClients = Enumerable.Range(0, parkerCount)
.Select(i => CarClient.Create(mqttClientFactory, new RandomParkerClientBehaviour(), physicalWorld, pgs, i, true));
.Select(i => CarClient.Create(mqttClientFactory, new RandomParkerClientBehaviour(), physicalWorld, pgs, i, false));
var parkers = await Task.WhenAll(parkerClients);

// init parkers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ public void DriveAlongPath(MockCar car)
else
{
// turn on next street
var overlap = car.Position.DistanceFromSource - car.Position.StreetEdge.Length;
car.Position.StreetEdge.DecrementCarCount();
car.Position = new StreetPosition(car.Path.First(), overlap);
car.Position.StreetEdge.IncrementCarCount();
car.Path = car.Path.Skip(1);

car.Turn(car.Path.First());
if(car.Logging)
Console.WriteLine($"{car}\ttick | {car.Position.ToString()} | dest: {car.Destination.Id} | car count: {car.Position.StreetEdge.CarCount} | driving at {car.Position.StreetEdge.CurrentMaxSpeed():F2}kmh/{car.Position.StreetEdge.SpeedLimit:F2}kmh");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public bool AttemptLocalParking(MockCar car)
passedParkingSpots.Pop();
}

// no free parking spot
if (passedParkingSpots.Count == 0) return false;

// occupy
Expand All @@ -60,7 +61,8 @@ public bool AttemptLocalParking(MockCar car)
// physically park
car.Position = new StreetPosition(car.Position.StreetEdge, nearestUnoccupiedSpot.DistanceFromSource);

car.Position.StreetEdge.DecrementCarCount();
// todo car.Position.StreetEdge.DecrementCarCount();

Random rand = new Random();
car.ParkTime = rand.Next(0, MockCar.MaxParkTime + 1);

Expand All @@ -69,6 +71,9 @@ public bool AttemptLocalParking(MockCar car)
car.KpiManager.DistanceTravelledParking += car.Position.DistanceFromSource;

// car.KpiManager.PublishAll(); TODO publish kpis with async and await
var sum =car.World.StreetEdges.Sum(edge => edge.CarCount);
Console.WriteLine($"sum: {sum}");

return true;
}

Expand Down
23 changes: 8 additions & 15 deletions src/Solution1/ConsoleApp1/sim/KpiManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,12 @@ public class KpiManager
public double DistanceTravelledParking { get; set; }

private readonly IMqttClient _mqttClient;
private MockCar _car;
private List<Kpi> _kpis;
private readonly MockCar _car;

public KpiManager(IMqttClient mqttClient, MockCar car)
{
_mqttClient = mqttClient;
_car = car;
_kpis = new List<Kpi>();
}

public void Reset()
Expand All @@ -45,12 +43,7 @@ public async Task Publish(Kpi kpi)
await _mqttClient.PublishAsync(new MqttApplicationMessage { Topic = kpi.Topic, Payload = kpi.Payload });
}

public byte[] Encode(string obj)
{
return Encoding.UTF8.GetBytes(obj);
}

public void PublishAll()
public async Task PublishAll()
{
// calc the rest
double distanceFromDestination = _car.Position.StreetEdge.Length - _car.Position.DistanceFromSource;
Expand All @@ -68,11 +61,11 @@ public void PublishAll()
int totalCo2EmissionsParking = (int)((DistanceTravelledParking / 1000) * Co2EmissionRate);

// add all
Publish(new Kpi("kpi/distFromDest", Encode(distanceFromDestination.ToString())));
Publish(new Kpi("kpi/distTravelledParking", Encode(DistanceTravelledParking.ToString())));
Publish(new Kpi("kpi/timeSpentParking", Encode(TicksSpentParking.ToString())));
Publish(new Kpi("kpi/speedReduction", Encode(SpeedReductionRunningAvg.ToString())));
Publish(new Kpi("kpi/fuelConsumption", Encode(totalFuelConsumptionParking.ToString())));
Publish(new Kpi("kpi/parkingEmissions", Encode(totalCo2EmissionsParking.ToString())));
await Publish(new Kpi("kpi/distFromDest", Encoding.UTF8.GetBytes(distanceFromDestination.ToString())));
await Publish(new Kpi("kpi/distTravelledParking", Encoding.UTF8.GetBytes(DistanceTravelledParking.ToString())));
await Publish(new Kpi("kpi/timeSpentParking", Encoding.UTF8.GetBytes(TicksSpentParking.ToString())));
await Publish(new Kpi("kpi/speedReduction", Encoding.UTF8.GetBytes(SpeedReductionRunningAvg.ToString())));
await Publish(new Kpi("kpi/fuelConsumption", Encoding.UTF8.GetBytes(totalFuelConsumptionParking.ToString())));
await Publish(new Kpi("kpi/parkingEmissions", Encoding.UTF8.GetBytes(totalCo2EmissionsParking.ToString())));
}
}
23 changes: 20 additions & 3 deletions src/Solution1/ConsoleApp1/sim/MockCar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,37 @@ public bool TargetNodeReached()

public void RespawnAtRandom()
{
Position.StreetEdge.DecrementCarCount();
// todo Position.StreetEdge.DecrementCarCount();
Position = StreetPosition.WithRandomDistance(World.StreetEdges.RandomElement());
Position.StreetEdge.IncrementCarCount();
// todo Position.StreetEdge.IncrementCarCount();
}

public void ResetAfterParking()
{
OccupiedSpot.Occupied = false;
Position.StreetEdge.IncrementCarCount();

// todo Position.StreetEdge.IncrementCarCount();

// kpi
KpiManager.Reset();

// diagnostics
World.IncrementUnoccupiedSpotCount();
}

public void Turn(StreetEdge next)
{
lock (Position.StreetEdge)
{
var overlap = Position.DistanceFromSource - Position.StreetEdge.Length;
var previousPosition = Position;
Position = new StreetPosition(next, overlap);
lock (Position.StreetEdge)
{
previousPosition.StreetEdge.DecrementCarCount();
Position.StreetEdge.IncrementCarCount();
}
Path = Path.Skip(1);
}
}
}
15 changes: 12 additions & 3 deletions src/Solution1/ConsoleApp1/sim/Street.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
using ConsoleApp1.sim.graph;
using ConsoleApp1.util;

namespace ConsoleApp1.sim;

public record Street
{
public required double Length { get; init; }
public int CarCount { get; set; }
public static double CarLength { get; } = 5.0;


public int CarCount { get; set; }

public required double SpeedLimit { get; init; }
public List<ParkingSpot> ParkingSpots { get; set; } = new List<ParkingSpot>();
public static double ParkingSpotDensity { get; set; } = 0.5; // between 0 and 1
Expand All @@ -19,7 +23,7 @@ public record Street
// todo
public double CurrentMaxSpeed()
{
lock (this)
lock(this)
{
double freeStreetLength = Length - CarCount * CarLength;
double recommendedSpeed = MathUtil.GetSafeSpeedMs(freeStreetLength / CarCount);
Expand All @@ -36,6 +40,7 @@ public double CurrentCoverDuration()
}
}

/*
public (bool parkingFound, int lastPassedOrFoundIndex) TryParkingLocally(double distanceFromSource,
int lastPassedIndex)
{
Expand Down Expand Up @@ -65,8 +70,9 @@ public void FreeParkingSpot(int spotIndex)
lock (this)
{
ParkingSpots[spotIndex].Occupied = false;
CarCount++;
}
Interlocked.Increment(ref _carCount);
}
private int CalculateLastPassedIndex(double distanceFromSource, int lastPassedIndex)
Expand All @@ -75,6 +81,9 @@ private int CalculateLastPassedIndex(double distanceFromSource, int lastPassedIn
(ParkingSpots[lastPassedIndex].Length + ParkingSpotSpacing));
return Math.Min(lastPassedIndexFromDistance, ParkingSpots.Count - 1);
}
*/



public void IncrementCarCount()
{
Expand Down
2 changes: 1 addition & 1 deletion src/Solution1/ConsoleApp1/sim/graph/StreetEdge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public string? StreetName
}
}

public int UnoccupiedSpotCount { get; set; }
public void InitParkingSpots(Dictionary<ParkingSpot, StreetEdge> parkingSpotMap)
{
int maxParkingSpots = (int)Math.Floor(Length / ParkingSpotLength);
Expand All @@ -45,7 +46,6 @@ public void InitParkingSpots(Dictionary<ParkingSpot, StreetEdge> parkingSpotMap)
ParkingSpots.ForEach(parkingSpot => parkingSpotMap.Add(parkingSpot, this));
}

public int UnoccupiedSpotCount { get; set; }

public required Dictionary<string, string?> Tags { get; init; }

Expand Down

0 comments on commit 899b698

Please sign in to comment.