v4 / vlib / sync / once.v
71 lines · 63 sloc · 1.55 KB · df24ab237ef04ddaf535d9b7253cfa8773771816
Raw
1module sync
2
3import sync.stdatomic
4
5pub struct Once {
6mut:
7 m RwMutex
8pub:
9 count u64
10}
11
12// new_once return a new Once struct.
13pub fn new_once() &Once {
14 mut once := &Once{}
15 once.m.init()
16 return once
17}
18
19// do executes the function `f()` only once, regardless of how many goroutines
20// call it concurrently. When do returns, f() has completed.
21// Note: if f() calls do on the same Once, it will deadlock.
22pub fn (mut o Once) do(f fn ()) {
23 if stdatomic.load_u64(&o.count) < 1 {
24 o.do_slow(f)
25 }
26}
27
28fn (mut o Once) do_slow(f fn ()) {
29 o.m.lock()
30 if o.count < 1 {
31 f()
32 stdatomic.store_u64(&o.count, 1)
33 }
34 o.m.unlock()
35}
36
37// do_with_param executes `f(param)` only once.
38// This method can be used as a workaround for passing closures to once.do/1 on Windows
39// (they are not implemented there yet) - just pass your data explicitly.
40// i.e. instead of:
41// ```v
42// once.do(fn [mut o] () {
43// o.add(5)
44// })
45// ```
46//
47// ... you can use:
48// ```v
49// once.do_with_param(fn (mut o One) {
50// o.add(5)
51// }, o)
52// ```
53
54// do_with_param executes the function `f(param)` only once, regardless of how
55// many goroutines call it concurrently. When do_with_param returns, f() has
56// completed.
57// Note: if f() calls do_with_param on the same Once, it will deadlock.
58pub fn (mut o Once) do_with_param(f fn (voidptr), param voidptr) {
59 if stdatomic.load_u64(&o.count) < 1 {
60 o.do_slow_with_param(f, param)
61 }
62}
63
64fn (mut o Once) do_slow_with_param(f fn (p voidptr), param voidptr) {
65 o.m.lock()
66 if o.count < 1 {
67 f(param)
68 stdatomic.store_u64(&o.count, 1)
69 }
70 o.m.unlock()
71}
72