require "phi" ; include Phi

p Thread.new{}

class RubyThread
  @@procs = []
  @@threads = []
  def initialize( &b )
    @@procs.push( b )
    return nil
  end
  
  def RubyThread.in_mainloop
    unless @@procs.empty?
      new_proc = @@procs.shift
      @@threads.push( Thread.new{ new_proc.call } )
    end
  end
  
  def RubyThread.threads
    @@threads
  end
end

form = Phi::Form.new
btn = Phi::Button.new form, :btn , "click to new thread ??"
btn.align = Phi::AL_CLIENT
btn.on_click = proc{
  RubyThread.new{
    no = RubyThread.threads.size
    label = Phi::Label.new form
    label.align = Phi::AL_TOP
    cnt = 0 unless cnt
    while Phi.alive?
      cnt+= 1
      label.caption = "no.#{no} "+cnt.to_s
      Phi::APPLICATION.process_messages
    end
  }
}

def mainloop2
  forms_size = Phi::SCREEN.forms.select{|f|f.visible}.size
  while Phi.alive?
    break if Phi::SCREEN.forms.select{|f|f.visible}.size < forms_size
    Phi::APPLICATION.process_messages
    RubyThread.in_mainloop
  end
end

form.show
mainloop2
raise
