Skip to content

Instantly share code, notes, and snippets.

@MaxPleaner
Created December 30, 2016 03:35
Show Gist options
  • Save MaxPleaner/555a64ff15c2f92bd3458b1cc42e600e to your computer and use it in GitHub Desktop.
Save MaxPleaner/555a64ff15c2f92bd3458b1cc42e600e to your computer and use it in GitHub Desktop.
limit total num threads
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