Created
November 5, 2021 08:46
-
-
Save pcreux/4f4049ef0fe8cfc4c65d26136448803b to your computer and use it in GitHub Desktop.
Simple multi-threading processing in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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