v / vlib / sync
Raw file | 33 loc (28 sloc) | 457 bytes | Latest commit hash e81e0ac70
1import sync
2
3struct One {
4pub mut:
5 i int
6}
7
8fn (mut o One) add(i int) {
9 o.i = o.i + i
10}
11
12fn run(mut once sync.Once, mut o One, c chan bool) {
13 once.do(fn [mut o] () {
14 o.add(5)
15 })
16 c <- true
17}
18
19fn test_once() {
20 mut o := &One{}
21 mut once := sync.new_once()
22 c := chan bool{}
23 n := 10
24
25 // It is executed 10 times, but only once actually.
26 for i := 0; i < n; i++ {
27 spawn run(mut once, mut o, c)
28 }
29 for i := 0; i < n; i++ {
30 <-c
31 }
32 assert o.i == 5
33}