(define *resource-counter* 0)

(define-record-type resource :resource
  (really-make-resource count align! lock)
  resource?
  (count resource-count)
  (align! resource-align!)
  (lock resource-lock))

(define (make-resource align! lock)
  (set! *resource-counter* (+ *resource-counter* 1))
  (really-make-resource *resource-counter* align! lock))

(define (with-resources-aligned resources thunk)
   (let ((locks (map resource-lock
                     (sort-list resources (lambda (r1 r2)
                                            (< (resource-count r1)
                                               (resource-count r2)))))))
     (for-each obtain-lock locks)
     (for-each
      (lambda (align!) (align!))
      (map resource-align! resources))
     (let ((val (with-handler
		 (lambda (cond more)
		   (for-each release-lock locks)
		   (more))
		 thunk)))
       (for-each release-lock locks)
       val)))