forked from ocaml-multicore/effects-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.ml
More file actions
50 lines (41 loc) · 1021 Bytes
/
transaction.ml
File metadata and controls
50 lines (41 loc) · 1021 Bytes
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
open Printf
type bottom
module type TXN = sig
type 'a t
val atomically : (unit -> unit) -> unit
val ref : 'a -> 'a t
val (!) : 'a t -> 'a
val (:=) : 'a t -> 'a -> unit
end
module Txn : TXN = struct
type 'a t = 'a ref
effect Update : 'a t * 'a -> unit
let atomically f =
let comp =
match f () with
| x -> (fun _ -> x)
| exception e -> (fun rb -> rb (); raise e)
| effect (Update (r,v)) k -> (fun rb ->
let old_v = !r in
r := v;
continue k () (fun () -> r := old_v; rb ()))
in comp (fun () -> ())
let ref = ref
let (!) = (!)
let (:=) = fun r v -> perform (Update (r,v))
end
exception Res of int
open Txn
let () = atomically (fun () ->
let r = ref 10 in
printf "T0: %d\n" (!r);
try atomically (fun () ->
r := 20;
r := 21;
printf "T1: Before abort %d\n" (!r);
raise (Res !r);
printf "T1: After abort %d\n" (!r);
r := 30)
with
| Res v -> printf "T0: T1 aborted with %d\n" v;
printf "T0: %d\n" !r)