« Back to Index

Ruby Thread speed and fail fast

View original Gist on GitHub

Ruby Thread speed and fail fast.rb

[:a, :b, :c].map { |i| 
  Thread.new { 
    sleep 5; i.upcase 
  } 
}.map { |i| i.value }

# If you call `Thread.new {}.value this would cause the overall time to take 15 seconds
# But calling `.value` once all the threads have completed mean the resulting time takes 5 seconds

Thread::abort_on_exception=true

[10, 10, 2].map { |i| 
  Thread.new { 
    sleep i; fail "a thing"; "success" 
  } 
}.map { |i| i.value }

# `Thread::abort_on_exception=true` causes the thread to fail fast if an exception is raised