Go语言 优雅的停工工人

5t7ly7z5  于 2023-05-20  发布在  Go
关注(0)|答案(1)|浏览(235)

下面的代码应该按照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
}
snvhrwxg

snvhrwxg1#

worker中的嵌套循环永远不会停止,我想Trock是想说。
同样在if err := srv.Shutdown(context.Background()); err != nil {中,你不应该传递ctx吗?
您可以考虑使用errgroup来捕获例程中的错误。

相关问题