summaryrefslogtreecommitdiff
path: root/shared_counter.kpl
blob: 01f01bd3a3206740fb93e188c534b7de61b0d97b (plain)
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
52
53
54
55
56
57

// Notice how counter can only be modified as read as [c]

counter : %shared 0

inc_dec : ([I64.amount]
    header : "#BOLD#Thread: %#, #WHITE#Counter:# " `format `thread_id
    body : ^ counter {[c]
        c +: amount
        ? {
            amount = 1 { "#GREEN#%#" `format c }
            amount = -1 { "#RED#%#" `format c }
            { "#UNDERLINE#INVALID#" }
        }
    }
    `log ,(header; body; "\n")
)

inc : inc_dec `bind 1
dec : inc_dec `bind -1

Inc_Dec_fn `type dec

actions : %const 1_000

batch : %const 100

runner : ([Inc_Dec_fn.fn]
    total : actions
    @ total {
        `log "#WHITE#Batch: #CYAN#% #MAGENTA#%#\n" `format (fn; total)
        v : Array[`async_type fn] $ ()
        @ 1 .. batch { v `push `async fn }
        @ v {[x] `await x }
        total -: batch
    }
)

i : runner `async inc
d : runner `async dec

`log "#BOLD#YELLOW#SLEEPING THREAD %#\n" `format `thread_id

`use "time" [Seconds]
`use "sys" [sleep]

sleep `sync Seconds $ 1

`await (d; i)

`log ^ counter {[c]
    ? !c {
        `format "#BOLD#GREEN#VALID#\n"
    } {
        `format "#BOLD#RED#INVALID#\n"
    }
}