1 | import sync |
2 | |
3 | // Note: this is the same test as `vlib/sync/once_test.v`, but |
4 | // it uses an explicit passing of the voidptr parameter in |
5 | // once.do_with_param/2, instead of passing a closure of it |
6 | // in once.do/1. |
7 | |
8 | struct One { |
9 | pub mut: |
10 | i int |
11 | } |
12 | |
13 | fn (mut o One) add(i int) { |
14 | o.i = o.i + i |
15 | } |
16 | |
17 | fn run(mut once sync.Once, mut o One, c chan bool) { |
18 | once.do_with_param(fn (mut o One) { |
19 | o.add(5) |
20 | }, o) |
21 | c <- true |
22 | } |
23 | |
24 | fn test_once() { |
25 | mut o := &One{} |
26 | mut once := sync.new_once() |
27 | c := chan bool{} |
28 | n := 10 |
29 | |
30 | // It is executed 10 times, but only once actually. |
31 | for i := 0; i < n; i++ { |
32 | spawn run(mut once, mut o, c) |
33 | } |
34 | for i := 0; i < n; i++ { |
35 | <-c |
36 | } |
37 | assert o.i == 5 |
38 | } |