Skip to content

Commit

Permalink
Make Effect.Ref thread-safe (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
f-f authored Feb 14, 2024
1 parent d4cf4e9 commit 9937583
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ jobs:
purescm run --main Test.Array.Main
purescm run --main Test.Console.Main
purescm run --main Test.Control.Main
purescm run --main Test.Effect.Ref.Main
purescm run --main Test.Foldable.Main
purescm run --main Test.Int.Main
purescm run --main Test.Lazy.Main
Expand Down
23 changes: 13 additions & 10 deletions refs/src/Effect/Ref.ss
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,41 @@
read
modifyImpl
write)
(import (prefix (chezscheme) scm:))
(import (prefix (chezscheme) scm:)
(prefix (purs runtime) rt:))

(scm:define _new
(scm:lambda (v)
(scm:lambda ()
(scm:box v))))
(scm:cons (scm:box v) (scm:make-mutex)))))

(scm:define newWithSelf
(scm:lambda (f)
(scm:lambda ()
(scm:let ([ref (scm:box (scm:quote ()))])
(scm:set-box! ref (f ref))
(scm:let ([ref (scm:cons (scm:box (scm:quote ())) (scm:make-mutex))])
(scm:set-box! (scm:car ref) (f ref))
ref))))

(scm:define read
(scm:lambda (ref)
(scm:lambda ()
(scm:unbox ref))))
(scm:unbox (scm:car ref)))))

(scm:define modifyImpl
(scm:lambda (f)
(scm:lambda (ref)
(scm:lambda ()
(scm:let* ([t (f (scm:unbox ref))]
[v (scm:hashtable-ref t "state" (scm:quote Effect.Ref:modifyImpl-CANT-GET-STATE))])
(scm:set-box! ref v)
v)))))
(scm:with-mutex (scm:cdr ref)
(scm:let* ([t (f (scm:unbox (scm:car ref)))]
[v (rt:record-ref t (scm:quote state))])
(scm:set-box! (scm:car ref) v)
v))))))

(scm:define write
(scm:lambda (val)
(scm:lambda (ref)
(scm:lambda ()
(scm:set-box! ref val)))))
(scm:with-mutex (scm:cdr ref)
(scm:set-box! (scm:car ref) val))))))

)

0 comments on commit 9937583

Please sign in to comment.