|
| 1 | +@doc raw""" |
| 2 | + DelayQueue{T} |
| 3 | +
|
| 4 | +A queue in which items are stored in a FIFO order, but are only available after a delay. |
| 5 | +
|
| 6 | +```jldoctest |
| 7 | +julia> sim = Simulation() |
| 8 | + queue = DelayQueue{Symbol}(sim, 10) |
| 9 | + @resumable function producer(env, queue) |
| 10 | + for item in [:a,:b,:a,:c] |
| 11 | + @info "putting $item at time $(now(env))" |
| 12 | + put!(queue, item) |
| 13 | + @yield timeout(env, 2) |
| 14 | + end |
| 15 | + end |
| 16 | + @resumable function consumer(env, queue) |
| 17 | + @yield timeout(env, 5) |
| 18 | + while true |
| 19 | + t = @yield take!(queue) |
| 20 | + @info "taking $(t) at time $(now(env))" |
| 21 | + end |
| 22 | + end |
| 23 | + @process producer(sim, queue) |
| 24 | + @process consumer(sim, queue) |
| 25 | + run(sim, 30) |
| 26 | +[ Info: putting a at time 0.0 |
| 27 | +[ Info: putting b at time 2.0 |
| 28 | +[ Info: putting a at time 4.0 |
| 29 | +[ Info: putting c at time 6.0 |
| 30 | +[ Info: taking a at time 10.0 |
| 31 | +[ Info: taking b at time 12.0 |
| 32 | +[ Info: taking a at time 14.0 |
| 33 | +[ Info: taking c at time 16.0 |
| 34 | +``` |
| 35 | +""" |
| 36 | +mutable struct DelayQueue{T} |
| 37 | + store::QueueStore{T, Int} |
| 38 | + delay::Float64 |
| 39 | +end |
| 40 | +function DelayQueue(env::Environment, delay) |
| 41 | + return DelayQueue(QueueStore{Any}(env), float(delay)) |
| 42 | +end |
| 43 | +function DelayQueue{T}(env::Environment, delay) where T |
| 44 | + return DelayQueue(QueueStore{T}(env), float(delay)) |
| 45 | +end |
| 46 | + |
| 47 | +@resumable function latency(env::Environment, channel::DelayQueue, value) |
| 48 | + @yield timeout(channel.store.env, channel.delay) |
| 49 | + put!(channel.store, value) |
| 50 | +end |
| 51 | + |
| 52 | +function Base.put!(channel::DelayQueue, value) |
| 53 | + @process latency(channel.store.env, channel, value) # start the process, but do not wait on it |
| 54 | +end |
| 55 | + |
| 56 | +function Base.take!(channel::DelayQueue) |
| 57 | + get(channel.store) |
| 58 | +end |
0 commit comments