To wait for a group of Goroutines to complete their tasks in Golang, you can use the sync.WaitGroup
package.
Here is an example of how to use sync.WaitGroup
:
import (
"sync"
)
sync.WaitGroup
:var wg sync.WaitGroup
wg.Add(1)
sync.WaitGroup
as an argument:go yourGoroutine(&wg)
Done()
on the sync.WaitGroup
:func yourGoroutine(wg *sync.WaitGroup) {
defer wg.Done()
// Your Goroutine logic here
}
Wait()
on the sync.WaitGroup
:wg.Wait()
By calling Wait()
, the program will block until all Goroutines have completed their tasks and called Done()
on the sync.WaitGroup
.
Make sure to initialize the sync.WaitGroup
before starting your Goroutines, increment the wait group counter before each Goroutine, call Done()
when a Goroutine completes its task, and call Wait()
to wait for all Goroutines to complete.