在 go 语言中,可以使用 context.context 和 context.cancelfunc 函数优雅地取消并发 goroutine:创建一个 context 和一个取消函数 cancel: ctx, cancel := context.withcancel(context.background())。创建一个 goroutine 并传递 ctx 作为参数。在需要时调用 cancel() 函数发送取消信号。使用 sync.waitgroup 等待 goroutine 退出。

Go 语言函数:如何优雅地取消并发 goroutine
在 Go 语言中,goroutine 是轻量级的并发单元。在某些情况下,我们需要在 goroutine 执行过程中将其取消。本文将介绍如何使用 context.Context 和 context.CancelFunc 函数优雅地取消并发 goroutine,并提供实战案例予以说明。
context.Context 和 context.CancelFunc
立即学习“go语言免费学习笔记(深入)”;
context.Context 提供了一种在 goroutine 之间传播取消信号的方法。它的 CancelFunc 方法用于发送取消信号。
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
// 创建并启动一个 goroutine
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
fmt.Println("Goroutine canceled")
return
default:
fmt.Println("Goroutine running")
}
}
}()
// 等待一段时间后取消 goroutine
time.Sleep(10 * time.Second)
cancel()
// 等待 goroutine 退出
wg.Wait()
}实战案例
该案例演示了如何使用 context.Context 取消一个 goroutine,goroutine 正处于一个无限循环中:
context 和一个取消函数 cancel: ctx, cancel := context.WithCancel(context.Background())。ctx 作为参数。goroutine 将进入一个无限循环,每秒打印 "Goroutine running"。cancel() 函数来发送取消信号。sync.WaitGroup 等待 goroutine 退出。当取消信号被发送时,goroutine 将优雅地退出并打印 "Goroutine canceled"。
以上就是Golang 函数:如何优雅地取消并发 goroutine?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号