package main
import (
"fmt”
"sync”
“time"
)
func process(i int, wg *sync.WaitGroup) {
fmt.Println("started Goroutine ", i)
time.Sleep(2 * time.Second)
fmt.Printf("Goroutine %d ended\n", i)
wg.Done()
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go process(i, &wg)
}
wg.Wait()
fmt.Println("All go routines finished executing”)
}
//main函数也可以写成如下方式
func main() {
var wg sync.WaitGroup
wg.Add(3) //设置计数器,数值即为goroutine的个数
go process(1, &wg)
go process(2, &wg)
go process(3, &wg)
wg.Wait() //主goroutine阻塞等待计数器变为0
fmt.Println("All goroutines finished executing")
}
命令行输出如下:
deer@192 src % go run hello.go //第1次
started Goroutine 3
started Goroutine 1
started Goroutine 2
Goroutine 2 ended
Goroutine 1 ended
Goroutine 3 ended
All goroutines finished executing
deer@192 src % go run hello.go //第2次
started Goroutine 3
started Goroutine 1
started Goroutine 2
Goroutine 1 ended
Goroutine 2 ended
Goroutine 3 ended
All goroutines finished executing
deer@192 src % go run hello.go //第3次
started Goroutine 3
started Goroutine 2
started Goroutine 1
Goroutine 3 ended
Goroutine 1 ended
Goroutine 2 ended
All goroutines finished executing