PasteRack.org
Paste # 67204
2017-05-06 17:24:21

Fork as a new paste.

Paste viewed 157 times.


Embed:

cross place atomic counter

  1. #lang racket/base
  2. (require ffi/unsafe)
  3.  
  4. (provide make-forever-counter-across-places
  5.          counter-add!)
  6.  
  7. (define (make-forever-counter-across-places)
  8.   ;; Fixnums can be stored in raw-malloc'ed memory:
  9.   (define b (box 0))
  10.   ;; A box representation is, um, certainly less than 256 bytes...
  11.   (define size 256)
  12.   (define m (malloc 'raw size))
  13.   (memcpy m (cast b _racket _pointer) size)
  14.   (cast m _pointer _racket))
  15.  
  16. (define (counter-add! c amt)
  17.   (let* ([n (unbox c)]
  18.          [new-n (+ n amt)])
  19.     (if (box-cas! c n new-n)
  20.         new-n
  21.         (counter-add! amt))))

=>