← 中文资源

简体中文版本

优雅响应 SIGINT 停止 worker

os/signal.Notify 注册 SIGINT/SIGTERM 到带缓冲 channel,worker 经 select 收信号后退出,defer signal.Stop 释放通知 goroutine 防泄漏。

阅读英文原文

实现说明

整个示例围绕函数 worker、main组织。 重复被限制在 for 里——其余代码按顺序各跑一遍。这里的并发就是一个 goroutine 加一个 channel——最小安全交接模式。defer 反转了通常的顺序——先登记、返回时执行——所以清理不会被漏掉。

使用要点

  • 跑完文件,输出里会留下标记——worker、shutdown complete。
  • main 的演示流程是 worker——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「优雅响应 SIGINT 停止 worker」会打印什么?

整个文件跑完,输出行以 worker、shutdown complete 这类前缀开头。

主签名形如 func worker(id int, stop <-chan os.Signal, done chan<- struct{})

核心语句

func worker(id int, stop <-chan os.Signal, done chan<- struct{}) {
	defer close(done)
	for {
		select {
		case <-stop:
			fmt.Println("worker", id, "stopped")
			return
		case <-time.After(100 * time.Millisecond):
			// 正常工作节拍
		}
	}
}
done := make(chan struct{})
stop := make(chan os.Signal, 1)

代码示例

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func worker(id int, stop <-chan os.Signal, done chan<- struct{}) {
	defer close(done)
	for {
		select {
		case <-stop:
			fmt.Println("worker", id, "stopped")
			return
		case <-time.After(100 * time.Millisecond):
			// 正常工作节拍
		}
	}
}

func main() {
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	// graceful shutdown: workers stop via the signal channel
	// 忘记 Stop 会让 notify 内部 goroutine 泄漏
	defer signal.Stop(stop)

	done := make(chan struct{})
	go worker(1, stop, done)

	// 演示:直接向 channel 送信号值;真实进程由内核递送
	time.Sleep(50 * time.Millisecond)
	stop <- syscall.SIGINT
	<-done
	fmt.Println("shutdown complete")
}