golang wait for goroutine to finish
To wait for a goroutine to finish in Go (Golang), you can use the sync.WaitGroup
package. Here are the steps to achieve this:
Import the sync package: Import the
sync
package at the beginning of your Go file by using the import statement:import "sync"
.Create a WaitGroup: Instantiate a new
sync.WaitGroup
using thevar wg sync.WaitGroup
statement.Add to the WaitGroup: Before starting the goroutines, call
wg.Add(1)
to increment the WaitGroup counter by 1 for each goroutine you plan to run.Launch the goroutine: Start the goroutine using the
go
keyword followed by the function call. For example,go myGoroutineFunction(wg)
.Inside the goroutine: At the end of the goroutine function, call
defer wg.Done()
to decrement the WaitGroup counter when the goroutine completes.Wait for the goroutines: After launching all goroutines, call
wg.Wait()
to block the execution of the main function until all goroutines have finished.
By following these steps, you can effectively wait for goroutines to finish in Go (Golang) using the sync.WaitGroup
package.