|
| 1 | +abstract type AbstractProcess <: AbstractEvent end |
| 2 | + |
| 3 | +struct EventKey |
| 4 | + time :: Float64 |
| 5 | + priority :: Int8 |
| 6 | + id :: UInt |
| 7 | +end |
| 8 | + |
| 9 | +function isless(a::EventKey, b::EventKey) :: Bool |
| 10 | + (a.time < b.time) || (a.time == b.time && a.priority > b.priority) || (a.time == b.time && a.priority == b.priority && a.id < b.id) |
| 11 | +end |
| 12 | + |
| 13 | +mutable struct Simulation <: Environment |
| 14 | + time :: Float64 |
| 15 | + heap :: DataStructures.PriorityQueue{BaseEvent, EventKey} |
| 16 | + eid :: UInt |
| 17 | + sid :: UInt |
| 18 | + active_proc :: Nullable{AbstractProcess} |
| 19 | + function Simulation(initial_time::Number=zero(Float64)) |
| 20 | + new(initial_time, DataStructures.PriorityQueue(BaseEvent, EventKey), zero(UInt), zero(UInt), Nullable{AbstractProcess}()) |
| 21 | + end |
| 22 | +end |
| 23 | + |
| 24 | +function now(sim::Simulation) |
| 25 | + sim.time |
| 26 | +end |
| 27 | + |
| 28 | +function active_process(sim::Simulation) :: AbstractProcess |
| 29 | + get(sim.active_proc) |
| 30 | +end |
| 31 | + |
| 32 | +function reset_active_process(sim::Simulation) |
| 33 | + sim.active_proc = Nullable{AbstractProcess}() |
| 34 | +end |
| 35 | + |
| 36 | +function set_active_process(sim::Simulation, proc::AbstractProcess) |
| 37 | + sim.active_proc = Nullable(proc) |
| 38 | +end |
| 39 | + |
| 40 | +struct StopSimulation <: Exception |
| 41 | + value :: Any |
| 42 | + function StopSimulation(value::Any=nothing) |
| 43 | + new(value) |
| 44 | + end |
| 45 | +end |
| 46 | + |
| 47 | +function stop_simulation(ev::AbstractEvent) |
| 48 | + throw(StopSimulation(value(ev))) |
| 49 | +end |
| 50 | + |
| 51 | +struct EmptySchedule <: Exception end |
| 52 | + |
| 53 | +function step(sim::Simulation) |
| 54 | + isempty(sim.heap) && throw(EmptySchedule()) |
| 55 | + (bev, key) = DataStructures.peek(sim.heap) |
| 56 | + DataStructures.dequeue!(sim.heap) |
| 57 | + sim.time = key.time |
| 58 | + bev.state = triggered |
| 59 | + while !isempty(bev.callbacks) |
| 60 | + DataStructures.dequeue!(bev.callbacks)() |
| 61 | + end |
| 62 | +end |
| 63 | + |
| 64 | +function run(sim::Simulation, until::AbstractEvent) |
| 65 | + append_callback(stop_simulation, until) |
| 66 | + try |
| 67 | + while true |
| 68 | + step(sim) |
| 69 | + end |
| 70 | + catch exc |
| 71 | + if isa(exc, StopSimulation) |
| 72 | + return exc.value |
| 73 | + else |
| 74 | + rethrow(exc) |
| 75 | + end |
| 76 | + end |
| 77 | +end |
| 78 | + |
| 79 | +function schedule(bev::BaseEvent, delay::Number=zero(Float64); priority::Int8=zero(Int8), value::Any=nothing) |
| 80 | + bev.value = value |
| 81 | + bev.env.heap[bev] = EventKey(bev.env.time + delay, priority, bev.env.sid+=one(UInt)) |
| 82 | + bev.state = scheduled |
| 83 | +end |
| 84 | + |
| 85 | +struct InterruptException <: Exception |
| 86 | + by :: AbstractProcess |
| 87 | + cause :: Any |
| 88 | +end |
0 commit comments