#!/usr/bin/env ruby
#
# Example of callcc (call with current continuation)

$threads = []

def sched
    callcc { |f|
        # save this current thread
        
        $threads.push(f)
        
        # remove the first from the list

        next_thread = $threads[0]
        $threads = $threads.slice(1, $threads.length)

        # start the new thread

        next_thread.call()
    }
    return
end

def start_thread
    callcc { |f|
        $threads.push(f)
        return
    }
    yield
end

start_thread {
    while true
        puts "I am thread one!"
        sched()
    end
}

start_thread {
    while true
        puts "I am thread two!"
        sched()
    end
}

while true
    puts "I am the main thread!"
    sched()
end


