Skip to content

Instantly share code, notes, and snippets.

@mgreenly
Last active October 30, 2019 02:08
Show Gist options
  • Save mgreenly/b93d2d50c39dc80bdfbd4393a73f5603 to your computer and use it in GitHub Desktop.
Save mgreenly/b93d2d50c39dc80bdfbd4393a73f5603 to your computer and use it in GitHub Desktop.
class Channel < SizedQueue
def initialize
super(1)
end
end
channel = Channel.new
Thread.new(channel) do |ch|
val = rand(3.0) + 1.0
sleep val
ch.push val
end
puts channel.pop
require 'concurrent/mvar'
q1 = Concurrent::MVar.new
q2 = Concurrent::MVar.new
def work
sleep rand(3.0)
end
Thread.new(q1) { |q| q.put work }
Thread.new(q2) { |q| q.put work }
result = [q1.take, q2.take]
puts result
class Promise
def initialize(*args, &block)
@thread = Thread.new(args) do |a|
@value = yield *a
end
end
def value
@thread.join
@value
end
end
def work
sleep rand(3.0)
end
promises = []
100.times do
promises << Promise.new { work }
end
result = promises.map(&:value)
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment