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:

  1. Import the sync package: Import the sync package at the beginning of your Go file by using the import statement: import "sync".

  2. Create a WaitGroup: Instantiate a new sync.WaitGroup using the var wg sync.WaitGroup statement.

  3. 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.

  4. Launch the goroutine: Start the goroutine using the go keyword followed by the function call. For example, go myGoroutineFunction(wg).

  5. Inside the goroutine: At the end of the goroutine function, call defer wg.Done() to decrement the WaitGroup counter when the goroutine completes.

  6. 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.