Stop Workers On SIGINT Gracefully

Register SIGINT and SIGTERM with os/signal.Notify, stop workers through the channel, and always call signal.Stop to release the notify goroutine.

GoResilience

Code

gosnippet
39 lines
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")
}

How it works

Count the functions worker and main as the entire surface area of Stop Workers On SIGINT Gracefully.

The cycling part of this snippet is for. Concurrency here is one goroutine plus one channel — the minimal safe handoff pattern. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Applying it

Entry signature: func worker(id int, stop <-chan os.Signal, done chan<- struct{})

The demo output is labeled (worker, shutdown complete), so each line traces straight back to the statement that printed it.

The demo flow inside main is worker — run the file to see it end to end.

Statements that matter

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)

Interactive Tools for This Topic

FAQ

What does Stop Workers On SIGINT Gracefully print when run?
Execute the whole file; each printed line is prefixed with a label like `worker`, `shutdown complete`.