Skip to content

Instantly share code, notes, and snippets.

@palkan
Last active June 9, 2018 16:59
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 palkan/21180569c75638059a294ba01d891dc8 to your computer and use it in GitHub Desktop.
Save palkan/21180569c75638059a294ba01d891dc8 to your computer and use it in GitHub Desktop.
[Saint-P RubyConf 2018] AsyncAwait in Ruby
# NOTE: gem install asynchronize
require "asynchronize"
module AsyncAwait
refine Module do
def async(mid)
include Asynchronize unless included_modules.include?(Asynchronize)
asynchronize mid
end
end
refine Kernel do
def await(*ths)
if ths.size == 1
ths.first.value
else
ths.map(&:value)
end
end
end
end
require "benchmark"
using AsyncAwait
class A
async def sleep!
t = rand * 2
sleep t
t
end
end
a = A.new
t = Benchmark.measure do
p await(a.sleep!, a.sleep!).sum
end
p t.real
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment