Created
December 8, 2022 11:37
-
-
Save haesbaert/0653e79a04a53af01348702340a07ee9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type 'a t = { | |
count : int Atomic.t; | |
data : 'a; | |
} | |
let make a = | |
{ count = Atomic.make 1; data = a } | |
let rec acquire t = | |
match Atomic.get t.count with | |
| 0 -> None | |
| old -> | |
if Atomic.compare_and_set t.count old (succ old) then | |
Some (t.data) | |
else | |
(Domain.cpu_relax (); acquire t) | |
let release t = | |
match Atomic.fetch_and_add t.count (-1) with | |
| 0 -> invalid_arg "double release" | |
| 1 -> true | |
| _v -> false | |
let maybe_with t f = | |
let () = match acquire t with | |
| Some data -> f data | |
| None -> () | |
in | |
release t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment