Skip to content

Instantly share code, notes, and snippets.

@haesbaert
Created December 8, 2022 11:37
Show Gist options
  • Save haesbaert/0653e79a04a53af01348702340a07ee9 to your computer and use it in GitHub Desktop.
Save haesbaert/0653e79a04a53af01348702340a07ee9 to your computer and use it in GitHub Desktop.
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