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