栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go 怎么等待所有的协程完成

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go 怎么等待所有的协程完成

1、通过Channel传递退出信号

channel作为go的一种基本数据类型,它有3种基本状态:nil、open、closed。

通过Channel共享数据,而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号,就像下面这样:func run(done chan int) {

for {

select {

case

fmt.Println("exiting...")

done

break

default:

}

time.Sleep(time.Second * 1)

fmt.Println("do something")

}

}

func main() {

c := make(chan int)

go run(c)

fmt.Println("wait")

time.Sleep(time.Second * 5)

c

fmt.Println("main exited")

}

2、使用waitgroup

通常情况下,我们像下面这样使用waitgroup:

1、创建一个Waitgroup的实例,假设此处我们叫它wg

2、在每个goroutine启动的时候,调用wg.Add(1),这个操作可以在goroutine启动之前调用,也可以在goroutine里面调用。当然,也可以在创建n个goroutine前调用wg.Add(n)

3、当每个goroutine完成任务后,调用wg.Done()

4、在等待所有goroutine的地方调用wg.Wait(),它在所有执行了wg.Add(1)的goroutine都调用完wg.Done()前阻塞,当所有goroutine都调用完wg.Done()之后它会返回。

示例:type Service struct {

// Other things

ch chan bool

waitGroup *sync.WaitGroup

}

func NewService() *Service {

s := &Service{

// Init Other things

ch: make(chan bool),

waitGroup: &sync.WaitGroup{},

}

return s

}

func (s *Service) Stop() {

close(s.ch)

s.waitGroup.Wait()

}

func (s *Service) Serve() {

s.waitGroup.Add(1)

defer s.waitGroup.Done()

for {

select {

case

fmt.Println("stopping...")

return

default:

}

s.waitGroup.Add(1)

go s.anotherServer()

}

}

func (s *Service) anotherServer() {

defer s.waitGroup.Done()

for {

select {

case

fmt.Println("stopping...")

return

default:

}

// Do something

}

}

func main() {

service := NewService()

go service.Serve()

// Handle SIGINT and SIGTERM.

ch := make(chan os.Signal)

signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

fmt.Println(

// Stop the service gracefully.

service.Stop()

}

更多golang知识请关注golang教程栏目。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/945724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号