Skip to content

Instantly share code, notes, and snippets.

@pcreux
Created November 5, 2021 08:46
Show Gist options
  • Save pcreux/4f4049ef0fe8cfc4c65d26136448803b to your computer and use it in GitHub Desktop.
Save pcreux/4f4049ef0fe8cfc4c65d26136448803b to your computer and use it in GitHub Desktop.
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