require 'thread' # If you use Sync instead then you don't have as much of a leak. # require 'sync' class TestThreads def initialize @guard = Mutex.new @start = Mutex.new # @guard = Sync.new @workers = ThreadGroup.new end def test @start.synchronize { @guard.lock # @guard.synchronize(:EX) { begin ta = [] 300.times {|i| ta << i } rescue Object puts "ERROR: #$!" end @guard.unlock } # } # end Sync end def run loop do # fire up threads until there's a thousand @start.lock STDERR.puts "Starting threads" until @workers.list.length >= 1000 @workers.add Thread.new { test } end @start.unlock until @workers.list.length == 0 STDERR.puts "waiting for #{@workers.list.length} threads" sleep 0.1 GC.start end STDERR.puts "Threads gone." end end end Thread.abort_on_exception=true tt = TestThreads.new tt.run