Created
August 7, 2019 05:15
-
-
Save ilhamarrouf/143cbd91c8635cea33c8ebfc3992d29c to your computer and use it in GitHub Desktop.
To wait for multiple goroutines to finish, we can use a wait group.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To wait for multiple goroutines to finish, we can | |
// use a *wait group*. | |
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
// This is the function we'll run in every goroutine. | |
// Note that a WaitGroup must be passed to functions by | |
// pointer. | |
func worker(id int, wg *sync.WaitGroup) { | |
fmt.Printf("Worker %d starting\n", id) | |
// Sleep to simulate an expensive task. | |
time.Sleep(time.Second) | |
fmt.Printf("Worker %d done\n", id) | |
// Notify the WaitGroup that this worker is done. | |
wg.Done() | |
} | |
func main() { | |
// This WaitGroup is used to wait for all the | |
// goroutines launched here to finish. | |
var wg sync.WaitGroup | |
// Launch several goroutines and increment the WaitGroup | |
// counter for each. | |
for i := 1; i <= 5; i++ { | |
wg.Add(1) | |
go worker(i, &wg) | |
} | |
// Block until the WaitGroup counter goes back to 0; | |
// all the workers notified they're done. | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment