Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Last active January 17, 2018 03:03
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 Aupajo/d03b20449afeea27c6b6059d431eee4b to your computer and use it in GitHub Desktop.
Save Aupajo/d03b20449afeea27c6b6059d431eee4b to your computer and use it in GitHub Desktop.
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
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