1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

sync.once: add Once (#12722)

This commit is contained in:
Taillook
2021-12-06 01:56:03 +09:00
committed by GitHub
parent 105d7fcf75
commit 0c713f6edc
3 changed files with 67 additions and 0 deletions

33
vlib/sync/once_test.v Normal file
View File

@@ -0,0 +1,33 @@
import sync
struct One {
pub mut:
i int
}
fn (mut o One) add(i int) {
o.i = o.i + i
}
fn run(mut once sync.Once, mut o One, c chan bool) {
once.do(fn [mut o] () {
o.add(5)
})
c <- true
}
fn test_once() {
mut o := &One{}
mut once := sync.new_once()
c := chan bool{}
n := 10
// It is executed 10 times, but only once actually.
for i := 0; i < n; i++ {
go run(mut once, mut o, c)
}
for i := 0; i < n; i++ {
<-c
}
assert o.i == 5
}