Skip to content

Instantly share code, notes, and snippets.

@pcreux
Created November 5, 2021 08:46
Embed
What would you like to do?
Simple multi-threading processing in ruby
results = []
queue = Queue.new
mutex = Mutex.new
THREAD_COUNT = 3
threads = Array.new(THREAD_COUNT) do
Thread.new do
while (value = queue.pop)
mutex.synchronize do
sleep 0.01
results << value + 1
end
end
end
end
100.times do
queue << rand(100)
end
queue.close # queue.pop will return `nil` once the queue is empty
threads.each(&:join) # wait for all threads to finish
pp results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment