Last active
October 30, 2019 02:08
-
-
Save mgreenly/b93d2d50c39dc80bdfbd4393a73f5603 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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