

require 'thread'
require 'delegate'




class StartableThread < SimpleDelegator

    def initialize(*args,&thread_proc)
        @args       = args
        @thread_proc= thread_proc
        @thread =  Thread.new {}    # dummy thread, does nothing
        super(@thread)
        nil
    end

    def start(*args)
        Thread.critical = true
        @thread.kill  if @thread.alive?
        Thread.critical = false
        
        @thread = Thread.new(args) {|args|@thread_proc.call(*args)}
        __setobj__(@thread)
        
        self
    end
    
    def stop
        @thread.kill
        self
    end
end



class RestartableThread_old < SimpleDelegator

    def initialize(*args,&thread_proc)
        @args       = args
        @thread_proc= thread_proc
        @thread =  Thread.new(*args) { 
            Thread.stop; 
            thread_proc.call(*args)
        }
        super(@thread)
        nil
    end

    def start
        Thread.critical = true
        if @thread.alive?
            @thread.wakeup
            Thread.critical = false
        else
            Thread.critical = false
            @thread = Thread.new(@args) {|args|@thread_proc.call(*args)}
            __setobj__(@thread)
        end
        self
    end
    
    def stop
        @thread.kill
        self
    end
end
