;; -*- Mode: Irken -*-

;; Can we use this simple coro to write samefringe? Can it even be
;;  done with a statically-typed call/cc?  Not in the simple way that
;;  we can in Python - since the run-queue would need to be able to
;;  store random objects in the queue?  I think samefringe really wants
;;  to be done with generators...

(include "lib/basis.scm")

(define run-queue (queue/make))

(define (enqueue k)
  (queue/add run-queue k))

(define (dispatch)
  (match (queue/pop run-queue) with
    (maybe:yes k) -> (putcc k #u)
    (maybe:no) -> #u))

(define (fork f)
  (enqueue (getcc))
  (f)
  (dispatch))

(define (yield)
  (enqueue (getcc))
  (dispatch))

(define (thread n)
  (for-range
      i 10
      (print-string (format "thread# " (int n) ":" (int i) "\n"))
      (yield)
      ))

(print-string "first fork\n")
(fork (lambda () (thread 0)))
(print-string "second fork\n")
(fork (lambda () (thread 1)))
(thread 2)
(print-string (format "queue length = " (int run-queue.length) "\n"))