safe-open-file.ss
#lang scheme/base

(require (prefix-in log: (planet synx/log:1))
         (prefix-in finalize: (planet synx/util:1/finalize)))

(define max-files (make-semaphore #x3f0))

(define (safe-open-input-file i name)
  (semaphore-wait max-files)
  (log:info "open ~s" i)
  (finalize:register (open-input-file name) 
                     (λ (v)
                       (log:info "close ~s" i)
                       (close-input-port v)
                       (semaphore-post max-files))))

(define (execute-hack)
  (thread
   (λ ()
     (let loop ()
       (sleep 1)
       (collect-garbage)
       (loop)))))
  

(define (sploof-one-file i)
  (define f (safe-open-input-file i "/dev/zero"))
  (log:info "~s ~s" i (read-bytes 4 f))
  (log:info "Done with ~s" i))
  
(define (main)
  (execute-hack)
  (for-each
   sync/enable-break
   (map thread-dead-evt
        (for/list ((i (in-range #x2000)))
          (thread
           (λ () (sploof-one-file i)))))))

(provide main)