v / vlib / sync
Raw file | 38 loc (32 sloc) | 672 bytes | Latest commit hash e81e0ac70
1import 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
8struct One {
9pub mut:
10 i int
11}
12
13fn (mut o One) add(i int) {
14 o.i = o.i + i
15}
16
17fn 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
24fn 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}