Golang中signal.NotifyContext的释放问题
Golang中signal.NotifyContext的释放问题
NotifyContext 将在哪个 Go 版本中发布?
// The stop function unregisters the signal behavior, which, like signal.Reset,
// may restore the default behavior for a given signal. For example, the default
// behavior of a Go program receiving os.Interrupt is to exit. Calling
// NotifyContext(parent, os.Interrupt) will change the behavior to cancel
// the returned context. Future interrupts received will not trigger the default
// (exit) behavior until the returned stop function is called.
//
// The stop function releases resources associated with it, so code should
// call stop as soon as the operations running in this Context complete and
// signals no longer need to be diverted to the context.
func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc) {
ctx, cancel := context.WithCancel(parent)
c := &signalCtx{
Context: ctx,
cancel: cancel,
signals: signals,
}
c.ch = make(chan os.Signal, 1)
Notify(c.ch, c.signals...)
if ctx.Err() == nil {
go func() {
更多关于Golang中signal.NotifyContext的释放问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
在下一个版本 Go 1.16 中:https://tip.golang.org/doc/go1.16#os/signal
通常,你可以通过查看 tip.golang.org 的发布说明、检查 GitHub 跟踪器上的问题,或者查看 Gerrit 上引入该更改的提交(例如:https://go-review.googlesource.com/c/go/+/219640)来了解这些信息。
更多关于Golang中signal.NotifyContext的释放问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
signal.NotifyContext 已在 Go 1.16 版本中正式发布。以下是示例代码:
package main
import (
"context"
"fmt"
"os"
"os/signal"
"time"
)
func main() {
// 创建父上下文
parentCtx := context.Background()
// 获取带有信号处理的上下文和停止函数
ctx, stop := signal.NotifyContext(parentCtx, os.Interrupt, os.Kill)
defer stop() // 确保资源被释放
// 模拟长时间运行的操作
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("Context cancelled")
return
default:
fmt.Println("Working...")
time.Sleep(1 * time.Second)
}
}
}()
// 等待上下文被取消
<-ctx.Done()
fmt.Println("Program exiting")
}
关键点:
stop()函数用于释放signal.NotifyContext分配的资源- 应该在使用完上下文后立即调用
stop()(通常使用defer) - 调用
stop()后,信号处理会恢复到默认行为 - 如果不调用
stop(),信号处理器会一直保持注册状态

