+(define (update-agenda-from-select! agenda)
+ (define (hash-keys selector)
+ (hash-map->list (lambda (k v) k) hash))
+ (define (get-wait-time)
+ ;; TODO: we need to figure this out based on whether there's anything
+ ;; in the queue, and if not, how long till the next scheduled item
+ (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
+ (cond
+ ((not (q-empty? (agenda-queue agenda)))
+ (values 0 0))
+ (soonest-time ; ie, the agenda is non-empty
+ (let* ((current-time (agenda-time agenda)))
+ (if (time-<= soonest-time current-time)
+ ;; Well there's something due so let's select
+ ;; (this avoids a (possible?) race condition chance)
+ (values 0 0)
+ (values
+ (- (car soonest-time) (car current-time))
+ (- (cdr soonest-time) (cdr current-time))))))
+ (else
+ (values #f #f)))))
+ (define (do-select)
+ ;; TODO: support usecond wait time too
+ (receive (sec usec)
+ (get-wait-time)
+ (select (hash-keys (agenda-read-port-map agenda))
+ (hash-keys (agenda-write-port-map agenda))
+ (hash-keys (agenda-except-port-map agenda))
+ sec usec)))
+ (define (get-procs-to-run)
+ (define (ports->procs ports port-map)
+ (lambda (initial-procs)
+ (fold
+ (lambda (port prev)
+ (cons (lambda ()
+ ((hash-ref port-map port) port))
+ prev))
+ initial-procs
+ ports)))
+ (match (do-select)
+ ((read-ports write-ports except-ports)
+ ;; @@: Come on, we can do better than append ;P
+ ((compose (ports->procs
+ read-ports
+ (agenda-read-port-map agenda))
+ (ports->procs
+ write-ports
+ (agenda-write-port-map agenda))
+ (ports->procs
+ except-ports
+ (agenda-except-port-map agenda)))
+ '()))))
+ (define (update-agenda)
+ (let ((procs-to-run (get-procs-to-run))
+ (q (agenda-queue agenda)))
+ (for-each
+ (lambda (proc)
+ (enq! q proc))
+ procs-to-run))
+ agenda)
+ (define (ports-to-select?)
+ (define (has-items? selector)
+ ;; @@: O(n)
+ ;; ... we could use hash-for-each and a continuation to jump
+ ;; out with a #t at first indication of an item
+ (not (= (hash-count (const #t)
+ (selector agenda))
+ 0)))
+ (or (has-items? agenda-read-port-map)
+ (has-items? agenda-write-port-map)
+ (has-items? agenda-except-port-map)))
+
+ (if (ports-to-select?)
+ (update-agenda)
+ agenda))
+
+
+(define* (start-agenda agenda
+ #:key stop-condition
+ (get-time gettimeofday)
+ (handle-ports update-agenda-from-select!))