counter.scm 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. ;; Counters
  2. ;;;; Copyright (C) 2017 Christopher Allan Webber <cwebber@dustycloud.org>
  3. ;;;;
  4. ;;;; This library is free software; you can redistribute it and/or
  5. ;;;; modify it under the terms of the GNU Lesser General Public
  6. ;;;; License as published by the Free Software Foundation; either
  7. ;;;; version 3 of the License, or (at your option) any later version.
  8. ;;;;
  9. ;;;; This library is distributed in the hope that it will be useful,
  10. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;;; Lesser General Public License for more details.
  13. ;;;;
  14. ;;;; You should have received a copy of the GNU Lesser General Public
  15. ;;;; License along with this library; if not, write to the Free Software
  16. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; General atomic counters; currently used for garbage collection.
  18. (define-module (fibers counter)
  19. #:use-module (ice-9 atomic)
  20. #:export (make-counter
  21. counter-decrement!
  22. counter-reset!))
  23. ;;; Counter utilities
  24. ;;;
  25. ;;; Counters here are an atomic box containing an integer which are
  26. ;;; either decremented or reset.
  27. ;; How many times we run the block-fn until we gc
  28. (define %countdown-steps 42) ; haven't tried testing for the most efficient number
  29. (define* (make-counter)
  30. (make-atomic-box %countdown-steps))
  31. (define (counter-decrement! counter)
  32. "Decrement integer in atomic box COUNTER."
  33. (let spin ((x (atomic-box-ref counter)))
  34. (let* ((x-new (1- x))
  35. (x* (atomic-box-compare-and-swap! counter x x-new)))
  36. (if (= x* x) ; successful decrement
  37. x-new
  38. (spin x*)))))
  39. (define (counter-reset! counter)
  40. "Reset a counter's contents."
  41. (atomic-box-set! counter %countdown-steps))