Golang控制子gorutine退出,并阻塞等待所有子gorutine全部退出
Golang控制子gorutine退出,并阻塞等待所有子gorutine全部退出
需求
程序有时需要自动重启或者重新初始化一些功能,就需要退出之前的所有子gorutine,并且要等待所有子gorutine全部退出,以下demo可以提供思路
实现demo
package main
import (
"fmt"
"sync"
"time"
)
func main() {
channal1 := make(chan bool,3)
wg := new(sync.WaitGroup)
wg.Add(3)
go g1(channal1,wg)
go g2(channal1,wg)
go g3(channal1,wg)
time.Sleep(time.Second * 10)
channal1 <- true
channal1 <- true
channal1 <- true
wg.Wait()
fmt.Println("++++>>>>all gorutine finish...<<<<++++")
close(channal1)
}
func g1(c chan bool,wg *sync.WaitGroup) {
i := 0
for{
select {
case <- c:
fmt.Printf("@@@---->>>>>g1 end<<<<<----+++\n")
wg.Done()
return
default:
i++
fmt.Printf("+++>>>>>g1 working---%d---<<<<<+++\n",i)
}
time.Sleep(time.Second * 2)
}
}
func g2(c chan bool,wg *sync.WaitGroup) {
i := 0
for{
select {
case <- c:
fmt.Printf("@@@---->>>>>g2 end<<<<<----+++\n")
wg.Done()
return
default:
i++
fmt.Printf("+++>>>>>g2 working---%d---<<<<<+++\n",i)
}
time.Sleep(time.Second * 2)
}
}
func g3(c chan bool,wg *sync.WaitGroup) {
i := 0
for{
select {
case <- c:
fmt.Printf("@@@---->>>>>g3 end<<<<<----+++\n")
wg.Done()
return
default:
i++
fmt.Printf("+++>>>>>g3 working---%d---<<<<<+++\n",i)
}
time.Sleep(time.Second * 2)
}
}
运行结果
+++>>>>>g2 working---1---<<<<<+++
+++>>>>>g1 working---1---<<<<<+++
+++>>>>>g3 working---1---<<<<<+++
+++>>>>>g2 working---2---<<<<<+++
+++>>>>>g1 working---2---<<<<<+++
+++>>>>>g3 working---2---<<<<<+++
+++>>>>>g2 working---3---<<<<<+++
+++>>>>>g1 working---3---<<<<<+++
+++>>>>>g3 working---3---<<<<<+++
+++>>>>>g2 working---4---<<<<<+++
+++>>>>>g1 working---4---<<<<<+++
+++>>>>>g3 working---4---<<<<<+++
+++>>>>>g2 working---5---<<<<<+++
+++>>>>>g3 working---5---<<<<<+++
+++>>>>>g1 working---5---<<<<<+++
@@@---->>>>>g2 end<<<<<----+++
@@@---->>>>>g1 end<<<<<----+++
@@@---->>>>>g3 end<<<<<----+++
++++>>>>all gorutine finish...<<<<++++