Addressing review comments
* Renamed the example * Reworded comments * Moved it to after worker pools * Sleep for a second instead of random * Mention the new sample in worker pools
This commit is contained in:
42
examples/waitgroup/waitgroup.go
Normal file
42
examples/waitgroup/waitgroup.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// 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 we're 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 WorkGroup
|
||||
// counter for each.
|
||||
for i := 1; i <= 5; i++ {
|
||||
wg.Add(1)
|
||||
go worker(i, &wg)
|
||||
}
|
||||
|
||||
// Block until the WorkGroup counter goes back to 0;
|
||||
// all the workers notified they're done.
|
||||
wg.Wait()
|
||||
}
|
||||
2
examples/waitgroup/waitgroup.hash
Normal file
2
examples/waitgroup/waitgroup.hash
Normal file
@@ -0,0 +1,2 @@
|
||||
ffc6520e73ebfa2b8c470e3ef00fee55388234e0
|
||||
8cD2V9CgI0J
|
||||
14
examples/waitgroup/waitgroup.sh
Normal file
14
examples/waitgroup/waitgroup.sh
Normal file
@@ -0,0 +1,14 @@
|
||||
$ go run waitgroup.go
|
||||
Worker 5 starting
|
||||
Worker 3 starting
|
||||
Worker 4 starting
|
||||
Worker 1 starting
|
||||
Worker 2 starting
|
||||
Worker 4 done
|
||||
Worker 1 done
|
||||
Worker 2 done
|
||||
Worker 5 done
|
||||
Worker 3 done
|
||||
|
||||
# The order of workers starting up and finishing
|
||||
# is likely to be different for each invocation.
|
||||
Reference in New Issue
Block a user