Created
April 20, 2020 01:05
-
-
Save HarlemSquirrel/7babaf8d9a90155d6ef30dbaa7ff51c7 to your computer and use it in GitHub Desktop.
Ruby thread concurrency limit demo
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
# The total number of threads we want to all to run at the same time | |
concurrent_thread_limit = 4 | |
# The total number of threads to run for this demo | |
total_thread_count = 13 | |
@threads = [] | |
## | |
# Print the status of all threads to the console | |
# | |
def print_threads_status(current = nil) | |
msg = Time.now.strftime('%H:%M:%S - ') | |
@threads.each_with_index do |t, i| | |
# A status of false indicates successfuly thread completion | |
# https://ruby-doc.org/core-2.6.5/Thread.html#method-i-status | |
status = (t.status || 'done') | |
msg << "#{i}: #{status}#{i == current ? '*' : ' '} ".ljust(10) | |
end | |
puts msg | |
end | |
# This will block until all threads have been created | |
total_thread_count.times do |i| | |
# Wait until there are fewer running threads then our limit | |
while @threads.count(&:alive?) >= concurrent_thread_limit | |
sleep 0.01 | |
end | |
# Create a new thread that starts running right away | |
@threads << Thread.new do | |
print_threads_status(i) | |
sleep 1 + rand | |
end | |
end | |
# Make sure all threads have completed by joining them to the main thread. | |
@threads.each(&:join) | |
puts "\nThreads are all joined now." | |
print_threads_status | |
puts "\nDone!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment