Skip to content

Instantly share code, notes, and snippets.

@lbarasti
Last active May 2, 2020 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbarasti/dab35d474ff55c68fdbb985a1d6147c9 to your computer and use it in GitHub Desktop.
Save lbarasti/dab35d474ff55c68fdbb985a1d6147c9 to your computer and use it in GitHub Desktop.
select use case 3: timeout on async calls
def log(msg)
puts "#{Fiber.current.name}: #{msg}"
end
Cache = Hash(Symbol, Float64?).new
def get_stock_price_async(sym : Symbol) : Channel(Float64)
Channel(Float64).new.tap { |ch|
spawn do
sleep rand
ch.send(rand)
end
}
end
def get_stock_price(sym : Symbol, max_wait : Time::Span)
select
when v = get_stock_price_async(sym).receive
log "received #{sym} price: #{v}"
Cache[sym] = v
when timeout max_wait
log "timed out, returning cached value for #{sym}"
Cache[sym]?
end
end
10.times {
log get_stock_price(:apl, 0.5.seconds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment