// 主函数内
go ready(5,&wg)// 函数
func ready(s int, wg *sync.WaitGroup)
1.
2.
3.
4.
• 同时在函数执行完成后,调用wg.Done,我们使用defer实现
defer wg.Done()
1.
完整代码
package main
import ("fmt""sync""time")
func ready(s int, wg *sync.WaitGroup){
defer wg.Done()
fmt.Printf("Run func in a goroutine and wait for %v\n", s)time.Sleep(time.Second*time.Duration(s))
fmt.Printf("Run func in a goroutine and wait for %v end\n", s)}
func main(){
var wg sync.WaitGroup
wg.Add(1)
go ready(5,&wg)
mainWaitSec :=2
fmt.Printf("Run Main function and wait for %v\n", mainWaitSec)time.Sleep(time.Second*time.Duration(mainWaitSec))
fmt.Printf("Run Main function and wait for %v done\n", mainWaitSec)
wg.Wait()}
var wg sync.WaitGroup
for i :=0; i <5; i++{
wg.Add(1)
waitSec := i +1
go func(){
defer wg.Done()
ready(waitSec)}()}
1.
2.
3.
4.
5.
6.
7.
8.
9.
完整代码
package main
import ("fmt""sync""time")
func ready(s int){
fmt.Printf("Run func in a goroutine and wait for %v\n", s)time.Sleep(time.Second*time.Duration(s))
fmt.Printf("Run func in a goroutine and wait for %v end\n", s)}
func main(){
var wg sync.WaitGroup
for i :=0; i <5; i++{
wg.Add(1)
waitSec := i +1
go func(){
defer wg.Done()
ready(waitSec)}()}
mainWaitSec :=2
fmt.Printf("Run Main function and wait for %v\n", mainWaitSec)time.Sleep(time.Second*time.Duration(mainWaitSec))
fmt.Printf("Run Main function and wait for %v done\n", mainWaitSec)
wg.Wait()}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
运行结果如下
Run Main function and wait for 2
Run func in a goroutine and wait for 2
Run func in a goroutine and wait for 4
Run func in a goroutine and wait for 5
Run func in a goroutine and wait for 1
Run func in a goroutine and wait for 3
Run func in a goroutine and wait for 1 end
Run Main function and wait for 2 done
Run func in a goroutine and wait for 2 end
Run func in a goroutine and wait for 3 end
Run func in a goroutine and wait for 4 end
Run func in a goroutine and wait for 5 end