golang协程如何关闭
Go  /  管理员 发布于 7年前   411
1、通过Channel传递退出信号
channel作为go的一种基本数据类型,它有3种基本状态:nil、open、closed。
通过Channel共享数据,而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号,就像下面这样:
func run(done chan int) { for { select { case <-done:fmt.Println("exiting...")done <- 1break 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 <- 1 <-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 <-s.ch:fmt.Println("stopping...")return default: } s.waitGroup.Add(1) go s.anotherServer()}}func (s *Service) anotherServer() { defer s.waitGroup.Done() for { select { case <-s.ch: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(<-ch) // Stop the service gracefully. service.Stop()}
更多golang知识请关注golang教程栏目。
以上就是golang协程如何关闭的详细内容,更多请关注其它相关文章!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号