Skip to content

Commit f62b5fd

Browse files
authored
sync: add implementation for WaitGroup.go/1, add test (#24797)
1 parent 3d320af commit f62b5fd

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

vlib/sync/waitgroup.c.v

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,14 @@ pub fn (mut wg WaitGroup) wait() {
8282
C.atomic_fetch_add_u32(voidptr(&wg.wait_count), 1)
8383
wg.sem.wait() // blocks until task_count becomes 0
8484
}
85+
86+
// go starts `f` in a new thread, arranging to call wg.add(1) before that,
87+
// and wg.done() in the same thread. The function `f` should not panic.
88+
// Calls to wg.go() should happen before the call to wg.wait().
89+
pub fn (mut wg WaitGroup) go(f fn ()) {
90+
wg.add(1)
91+
spawn fn (mut wg WaitGroup, f fn ()) {
92+
f()
93+
wg.done()
94+
}(mut wg, f)
95+
}

vlib/sync/waitgroup_test.v

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,16 @@ fn test_waitgroup_no_use() {
3939
wg.wait()
4040
done = true
4141
}
42+
43+
fn test_waitgroup_go() {
44+
mut counter := 0
45+
p := unsafe { &counter }
46+
mut wg := new_waitgroup()
47+
for i in 0 .. 10 {
48+
wg.go(fn [p] () {
49+
unsafe { (*p)++ }
50+
})
51+
}
52+
wg.wait()
53+
assert counter == 10
54+
}

0 commit comments

Comments
 (0)