怎么关闭golang协程

发布时间:2020-06-10 10:43:33 作者:Leah
来源:亿速云 阅读:2107

这篇文章给大家分享的是关闭golang协程的方法。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

1、通过Channel传递退出信号

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

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

func run(done chan int) {
        for {
                select {
                case <-done:
                        fmt.Println("exiting...")
                        done <- 1
                        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 <- 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协程的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. lua 协程
  2. golang协程池设计详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

golang go语言 协程

上一篇:如何解决linux修改hosts文件不生效问题

下一篇:checkpoint R80初始化安装和smartconsole安装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》