下面的代码应该按照gracefully-shutting-down-multiple-workers-in-go#coordinating-with-context中的示例工作
这里的bug在哪里,为什么当我按Ctrl+C(sigint)时它根本没有停止?
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var wg sync.WaitGroup
go func() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
<-signals
cancel()
}()
wg.Add(1)
go func() {
if err := myWorker(ctx); err != nil {
cancel()
}
wg.Done()
}()
wg.Add(1)
go func() {
if err := startServer(ctx); err != nil {
cancel()
}
wg.Done()
}()
wg.Wait()
}
func myWorker(ctx context.Context) error {
shouldStop := false
go func() {
<-ctx.Done()
shouldStop = true
}()
for !shouldStop {
for {
fmt.Println("https://gosamples.dev is the best")
time.Sleep(1 * time.Second)
}
}
return nil
}
func startServer(ctx context.Context) error {
var srv http.Server
go func() {
<-ctx.Done() // Wait for the context to be done
// Shutdown the server
if err := srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
log.Printf("HTTP server Shutdown: %v", err)
}
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
return fmt.Errorf("HTTP server ListenAndServe: %w", err)
}
return nil
}
1条答案
按热度按时间snvhrwxg1#
worker中的嵌套循环永远不会停止,我想Trock是想说。
同样在
if err := srv.Shutdown(context.Background()); err != nil {
中,你不应该传递ctx
吗?您可以考虑使用errgroup来捕获例程中的错误。