Source file treiber_stack.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(** Treiber's Lock Free stack *)
type 'a node = Nil | Next of 'a * 'a node
type 'a t = { head : 'a node Atomic.t }
let create () =
let head = Nil in
{ head = Atomic.make head }
let is_empty q = match Atomic.get q.head with Nil -> true | Next _ -> false
let push q v =
let head = Atomic.get q.head in
let new_node = Next (v, head) in
if Atomic.compare_and_set q.head head new_node then ()
else
let b = Backoff.create () in
Backoff.once b;
let rec loop b =
let head = Atomic.get q.head in
let new_node = Next (v, head) in
if Atomic.compare_and_set q.head head new_node then ()
else (
Backoff.once b;
loop b)
in
loop b
let pop q =
let rec loop b =
let s = Atomic.get q.head in
match s with
| Nil -> None
| Next (v, next) ->
if Atomic.compare_and_set q.head s next then Some v
else (
Backoff.once b;
loop b)
in
let s = Atomic.get q.head in
match s with
| Nil -> None
| Next (v, next) ->
if Atomic.compare_and_set q.head s next then Some v
else
let b = Backoff.create () in
Backoff.once b;
loop b