Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created February 3, 2025 17:59
Show Gist options
  • Save ismasan/b4c43cfafd8f411968cdf8f2c9a9a09d to your computer and use it in GitHub Desktop.
Save ismasan/b4c43cfafd8f411968cdf8f2c9a9a09d to your computer and use it in GitHub Desktop.
require 'thread'
def work(queue, &block)
Thread.new do
block.call(queue)
queue << :done
rescue StandardError => e
queue << e
end
end
def start
workers = []
queue = Queue.new
# Linearize the work
done_count = 0
# Produce some work
workers << work(queue) do |q|
10.times do |i|
sleep 1
raise ArgumentError, 'error' if i == 5
q << "thread 1: #{i}"
end
end
workers << work(queue) do |q|
20.times do |i|
sleep 0.5
q << "thread 2: #{i}"
end
end
while (data = queue.pop)
if data == :done
done_count += 1
break if done_count == workers.size
elsif data.is_a?(Exception)
# Linenarized error handling
# optionally re-raise here
p [:exception, data]
raise data
else
puts data
end
end
# rescue exceptions re-raised from threads here
rescue ArgumentError => e
p [:rescued, e]
ensure
puts 'byebug'
end
start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment