Created
December 30, 2016 03:35
-
-
Save MaxPleaner/555a64ff15c2f92bd3458b1cc42e600e to your computer and use it in GitHub Desktop.
limit total num threads
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
THREAD_LIMIT = ENV["THREAD_LIMIT"].to_i || 10 | |
THREAD = {count: 0} | |
class TooManyThreadsError < StandardError; end | |
class Thread | |
def new(*args, &blk) | |
too_many_threads_error if THREAD[:count] > THREAD_LIMIT | |
THREAD["count"] += 1 | |
super(*args, &->{blk.call; THREAD["count"] -= 1}) | |
end | |
end | |
10.times { Thread.new { sleep 1 } } | |
begin | |
Thread.new { } | |
rescue TooManyThreadsError | |
puts "rescued as expected" | |
end | |
sleep 1 | |
Thread.new { sleep 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment