我如何等待beego中的goroutines终止

我有 n 个 goroutine 在任务通道上等待。这些 goroutine 负责执行这些任务。目前,我使用 beego 作为我的 web golang 框架。我什么时候在 beego 应用程序中向我的 goroutine 发出终止信号?收到服务终止请求时如何推断?



隔江千里
浏览 140回答 1
1回答

慕的地8271018

作为第一步,让我们创建一个通道并将其绑定到您感兴趣的领域中的信号。然后您需要创建上下文并在收到此信号时触发取消功能。c := make(chan os.Signal, 1)signal.Notify(c, os.Interrupt)ctx, cancel := context.WithCancel(context.Background()) // pass your ctx in all goroutines as first argument,&nbsp;go func() {&nbsp; &nbsp; signal := <-c&nbsp; &nbsp; logger.Info("signal was received", zap.Stringer("signal", signal)&nbsp; &nbsp; cancel()}()然后,您可以创建WaitGroup上下文并将其作为每个 goroutine 中的第一个参数传递wg := &sync.WaitGroup{}hooks.RunStartHooks(ctx, wg)在您的工作人员内部,按照文档中的规定,聆听与 wg 一起正常工作的上下文取消for {&nbsp; &nbsp; select {&nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; // other cases}最后,&nbsp; &nbsp; timeout := cfg.Server.HooksCloseTimeout // this is from your config&nbsp;&nbsp; &nbsp; if waitTimeout(wg, timeout) {&nbsp; &nbsp; &nbsp; &nbsp; logger.Info("timed out waiting for wait group")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; logger.Info("server exited properly")&nbsp; &nbsp; }waitTimeout 在哪里// waitTimeout waits for the waitgroup for the specified max timeout.// Returns true if waiting timed out.func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {&nbsp; &nbsp; c := make(chan struct{})&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer close(c)&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; }()&nbsp; &nbsp; select {&nbsp; &nbsp; case <-c:&nbsp; &nbsp; &nbsp; &nbsp; return false // completed normally&nbsp; &nbsp; case <-time.After(timeout):&nbsp; &nbsp; &nbsp; &nbsp; return true // timed out&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go