require 'rubygems'
require 'fastthread' if ARGV.include?('fast')
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
    #  @guard = Sync.new
    @workers = ThreadGroup.new
  end

  def test
    @guard.lock
    # @guard.synchronize(:EX) {

    begin
      ta = []
      30000.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
      STDERR.puts "Starting threads"
      until @workers.list.length >= 1000
        @workers.add Thread.new { test }
      end

      until @workers.list.length == 0
        STDERR.puts "waiting for #{@workers.list.length} threads"
        sleep 10
        GC.start
      end

      STDERR.puts "Threads gone."
    end
  end

end

tt = TestThreads.new
tt.run