From f62b5fd7f27c067144236eb8722c89ee91a9b2c5 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 27 Jun 2025 02:03:07 +0300 Subject: [PATCH] sync: add implementation for WaitGroup.go/1, add test (#24797) --- vlib/sync/waitgroup.c.v | 11 +++++++++++ vlib/sync/waitgroup_test.v | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/vlib/sync/waitgroup.c.v b/vlib/sync/waitgroup.c.v index 6ed3076164..507789cf65 100644 --- a/vlib/sync/waitgroup.c.v +++ b/vlib/sync/waitgroup.c.v @@ -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) +} diff --git a/vlib/sync/waitgroup_test.v b/vlib/sync/waitgroup_test.v index cc473f5e57..6afed8cf3c 100644 --- a/vlib/sync/waitgroup_test.v +++ b/vlib/sync/waitgroup_test.v @@ -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 +}