Thread leak?

The following code seems to leak threads. Is there a better way to handle
timeouts so they don't leak threads? I tested it on both windows and linux
and the results are the same.

If you set t to nil in the rescue the result is the same.

      Adam

require 'timeout'

include ObjectSpace

begin

  execLine = "sleep 100"

  while true do

    t = Thread.new {

      begin

        e = IO.popen(execLine)

        e.readlines

      ensure

        e.close if (e && !e.closed?)

      end

    }

    begin

      timeout(1) { t.join }

    rescue TimeoutError => e

      puts "timeout: "+e.to_s

      t.kill

    end

    c = 0

    ObjectSpace.garbage_collect

    ObjectSpace.each_object{|t| c += 1 if t.class == Thread}

    puts "num threads #{c}"

    break if c > 20

  end

end

Hi,

At Fri, 14 Oct 2005 02:16:15 +0900,
Adam Beguelin wrote in [ruby-talk:160449]:

begin
  execLine = "sleep 100"
  while true do
    t = Thread.new {
      begin
        e = IO.popen(execLine)
        e.readlines
      ensure

          if e && !e.closed?
            Process.kill(e.pid)
            e.close
          end

···

      end
    }
    
    begin
      timeout(1) { t.join }
    rescue TimeoutError => e
      puts "timeout: "+e.to_s
      t.kill
    end
    c = 0
    ObjectSpace.garbage_collect
    ObjectSpace.each_object{|t| c += 1 if t.class == Thread}
    puts "num threads #{c}"
    break if c > 20
  end
end

--
Nobu Nakada