Skip to content

Instantly share code, notes, and snippets.

@kevinmcconnell
Last active January 2, 2016 21:49
Show Gist options
  • Save kevinmcconnell/8365521 to your computer and use it in GitHub Desktop.
Save kevinmcconnell/8365521 to your computer and use it in GitHub Desktop.
Simple queued concurrency pattern
class AsyncPool
def initialize
@threads = {}
@results = {}
end
def run(id, &block)
@threads[id] = Thread.new { @results[id] = block.call }
end
def result(id)
@threads[id].join
@results[id]
end
end
pool = AsyncPool.new
pool.run(:one) { sleep 2; "one" }
pool.run(:two) { sleep 4; "two" }
pool.run(:three) { sleep 8; "three" }
puts pool.result(:two)
puts pool.result(:one)
puts pool.result(:three)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment