require "phi" ; include Phi

class RubyThread
  @@procs = []
  @@threads = []
  def initialize( &b )
    @@procs.push( b )
    return nil
  end
  
  def RubyThread.in_mainloop
    until @@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 = AL_CLIENT
btn.on_click = proc{
  RubyThread.new{
    no = RubyThread.threads.size
    label=Phi::Label.new form
    label.align = AL_TOP
    cnt = 0 unless cnt
    while Phi.alive?
      p cnt += 1
      label.caption = "no.#{no} "+cnt.to_s
      APPLICATION.process_messages
    end
  }
}

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

form.show
mainloop2
raise
