| 1 | // vtest build: !windows && (amd64 || arm64) |
| 2 | import sync |
| 3 | |
| 4 | struct Counter { |
| 5 | pub mut: |
| 6 | i int |
| 7 | } |
| 8 | |
| 9 | fn (mut c Counter) add(i int) { |
| 10 | c.i = c.i + i |
| 11 | } |
| 12 | |
| 13 | fn run(mut m sync.ManyTimes, mut co Counter, c chan bool) { |
| 14 | m.do(fn [mut co] () { |
| 15 | co.add(5) |
| 16 | }) |
| 17 | c <- true |
| 18 | } |
| 19 | |
| 20 | fn test_many_times_once() { |
| 21 | mut co := &Counter{} |
| 22 | mut m := sync.new_many_times(1) |
| 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 m, mut co, c) |
| 29 | } |
| 30 | for i := 0; i < n; i++ { |
| 31 | <-c |
| 32 | } |
| 33 | assert co.i == 5 |
| 34 | } |
| 35 | |
| 36 | fn test_many_times_fifth() { |
| 37 | mut co := &Counter{} |
| 38 | mut m := sync.new_many_times(5) |
| 39 | c := chan bool{} |
| 40 | n := 10 |
| 41 | |
| 42 | // It is executed 10 times, but only 5 times actually. |
| 43 | for i := 0; i < n; i++ { |
| 44 | spawn run(mut m, mut co, c) |
| 45 | } |
| 46 | for i := 0; i < n; i++ { |
| 47 | <-c |
| 48 | } |
| 49 | assert co.i == 25 |
| 50 | } |
| 51 | |