fibers icon indicating copy to clipboard operation
fibers copied to clipboard

Possibly wrong usage of atomic-box-set!

Open cireu opened this issue 4 years ago • 0 comments

https://github.com/wingo/fibers/blob/master/fibers/scheduler.scm#L272

I see (atomic-box-set! box (+ (atomic-box-ref ...) ...)) pattern here, but IIUC this will cause race condition in multithreading context, the box maybe update after atomic-box-ref and before atomic-box-set! by other threads.

I think this implementation is correct

(define update-count-box (box)
  (let retry ((old-box-val (atomic-box-ref box)))
    (let ((new-val (logand (1+ old-box-val) #xffffFFFF))
          (cur-box-val (atomic-box-compare-and-swap! box old-box-val new-val)))
      (if (eq? cur-box-val new-val)
          new-val
          (retry cur-box-val)))))

cireu avatar Jun 29 '21 14:06 cireu