Created
December 26, 2014 02:19
-
-
Save tiancaiamao/69979608cb5b7de1116b to your computer and use it in GitHub Desktop.
协程
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(define ready-queue '()) | |
(define list-append | |
(lambda (ls x) | |
(if (null? ls) | |
(cons x '()) | |
(cons (car ls) (list-append (cdr ls) x))))) | |
;; 定义队列操作的函数 | |
(define enqueue list-append) | |
(define queue-empty? null?) | |
(define queue-head car) | |
(define dequeue cdr) | |
(define yield | |
(lambda () | |
(call/cc | |
(lambda (cont) | |
(if (queue-empty? ready-queue) | |
(cont) ;;继续运行下去,yield不生效 | |
(let ((run (queue-head ready-queue)) | |
(newq (enqueue (dequeue ready-queue) cont))) | |
(set! ready-queue newq) | |
(run))))))) | |
(define print | |
(lambda (x) | |
(let loop ((i 0)) | |
(if (= i 10) | |
42 | |
(begin | |
(printf "~a\n" x) | |
(yield) | |
(loop (+ i 1))))))) | |
(set! ready-queue (enqueue ready-queue (lambda () (print "a")))) | |
(set! ready-queue (enqueue ready-queue (lambda () (print "b")))) | |
(print "c") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment