Last active
January 17, 2018 03:03
-
-
Save Aupajo/d03b20449afeea27c6b6059d431eee4b to your computer and use it in GitHub Desktop.
This file contains 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 'thread' | |
def thing_yielder(&block) | |
things = %i( a b c ) | |
yieldings = Queue.new | |
threads = things.map do |thing| | |
Thread.new do | |
sleep rand(1..3) # Simulate work | |
yieldings << thing | |
end | |
end | |
threads.each(&:join) | |
while thing = yieldings.shift(true) rescue nil | |
yield thing | |
end | |
end | |
puts "Main thread: #{Thread.current.object_id}" | |
thing_yielder do |thing| | |
puts "Thread #{thing} yielded with thread #{Thread.current.object_id}" | |
end | |
# Main thread: 70313379624840 | |
# Thread a yielded with thread 70313379624840 | |
# Thread b yielded with thread 70313379624840 | |
# Thread c yielded with thread 70313379624840 |
This file contains 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 'thread' | |
def thing_yielder | |
things = %i( a b c ) | |
threads = things.map do |thing| | |
Thread.new do | |
sleep rand(1..3) | |
yield thing | |
end | |
end | |
threads.each(&:join) | |
end | |
puts "Main thread: #{Thread.current.object_id}" | |
thing_yielder do |thing| | |
puts "Thread #{thing} yielded with thread #{Thread.current.object_id}" | |
end | |
# Main thread: 70325593438120 | |
# Thread a yielded with thread 70325610046980 | |
# Thread b yielded with thread 70325610046460 | |
# Thread c yielded with thread 70325610046180 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment