sync: add implementation for WaitGroup.go/1, add test (#24797)

This commit is contained in:
Delyan Angelov 2025-06-27 02:03:07 +03:00 committed by GitHub
parent 3d320afa65
commit f62b5fd7f2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 0 deletions

View File

@ -82,3 +82,14 @@ pub fn (mut wg WaitGroup) wait() {
C.atomic_fetch_add_u32(voidptr(&wg.wait_count), 1)
wg.sem.wait() // blocks until task_count becomes 0
}
// go starts `f` in a new thread, arranging to call wg.add(1) before that,
// and wg.done() in the same thread. The function `f` should not panic.
// Calls to wg.go() should happen before the call to wg.wait().
pub fn (mut wg WaitGroup) go(f fn ()) {
wg.add(1)
spawn fn (mut wg WaitGroup, f fn ()) {
f()
wg.done()
}(mut wg, f)
}

View File

@ -39,3 +39,16 @@ fn test_waitgroup_no_use() {
wg.wait()
done = true
}
fn test_waitgroup_go() {
mut counter := 0
p := unsafe { &counter }
mut wg := new_waitgroup()
for i in 0 .. 10 {
wg.go(fn [p] () {
unsafe { (*p)++ }
})
}
wg.wait()
assert counter == 10
}