一 优雅退出
Go语言中的优雅退出指的是在程序关闭时,确保所有的后台任务或协程能够安全地完成当前工作并释放资源,而不是直接被强制终止。实现优雅退出通常使用
context包来传递取消信号,以及sync.WaitGroup来等待所有协程完成。通过这种方式,可以确保程序在退出时不会丢失数据或留下未完成的任务。二 WaitGroup
这里使用go的waitGroup实现优雅退出。
相关文档:
使用实例
package main import ( "fmt" "sync" "time" ) func worker(id int) { fmt.Printf("Worker %d starting\n", id) time.Sleep(time.Second) fmt.Printf("Worker %d done\n", id) } func main() { var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go func() { defer wg.Done() worker(i) }() } wg.Wait() }
这里创建五个线程来睡眠。这个 WaitGroup 用于等待这里启动的所有 goroutine 完成。启动多个 goroutine 并增加每个 goroutine 的 WaitGroup 计数器。阻塞直到 WaitGroup 计数器返回到 0。
在运行中对go发送kill -15信号退出。观察退出时输出。可以看到所有线程都执行了全部的内容。
$ go run waitgroups.go Worker 5 starting Worker 3 starting Worker 4 starting Worker 1 starting Worker 2 starting Worker 4 done Worker 1 done Worker 2 done Worker 5 done Worker 3 done
操作原理
Add() is used to add the number of goroutines that need to be waited upon.
Done() is called by each goroutine when it finishes its work, decrementing the internal counter of the wait group.
Wait() is used to block the execution of the goroutine until all the goroutines have called Done().
