在Go语言中,context
包是用来处理上下文的,它可以帮助控制取消操作、超时、截止时间等。下面是一个简单的使用 context
来控制超时的例子:
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建一个超时的上下文,超时时间为1秒
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel() // 确保在main函数结束时取消上下文,释放资源
// 模拟一个耗时操作
select {
case <-time.After(2 * time.Second): // 模拟耗时操作,这里设置为2秒
fmt.Println("Operation completed")
case <-ctx.Done(): // 如果上下文超时,会触发这个case
fmt.Println("Operation canceled due to timeout")
}
}
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建一个可以取消的 context
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 确保主函数退出时取消 context
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("Goroutine 被取消")
return
default:
fmt.Println("Goroutine 正在运行")
time.Sleep(500 * time.Millisecond)
}
}
}()
time.Sleep(2 * time.Second) // 主 goroutine 等待 2 秒
cancel() // 手动取消 context
time.Sleep(1 * time.Second) // 等待 goroutine 完成
fmt.Println("主程序结束")
}
引入协程处理
// Context
package main
import (
"context"
"fmt"
"time"
)
func doWork(ctx context.Context) {
select {
case <-time.After(4 * time.Second): // 模拟耗时操作
fmt.Println("Work done")
case <-ctx.Done(): // 检查是否收到取消信号
fmt.Println("Work canceled")
}
}
func main() {
// 打印当前时间
fmt.Println("Current time:", time.Now().Format(time.RFC1123))
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go doWork(ctx) // 在一个新的goroutine中执行耗时操作
// 等待超时或工作完成
<-ctx.Done()
fmt.Println("Main function: Work is done or canceled")
}
为什么 Work canceled没有打印
测试
package main
import (
"context"
"fmt"
"time"
)
// 在您提供的代码中,Work canceled 没有打印的原因是因为 doWork 函数中的 select 语句没有正确处理 ctx.Done() 通道。具体来说,select 语句中的两个 case 都使用了 <-time.After 和 <-ctx.Done(),这意味着 select 会等待两个通道中的任何一个发送值。由于 time.After 会发送值,所以 select 会优先执行第一个 case,导致 doWork 函数不会检测到 ctx.Done() 通道的值。
func doWork(ctx context.Context) {
select {
case <-time.After(4 * time.Second): // 模拟耗时操作
fmt.Println("Work done")
case <-ctx.Done(): // 检查是否收到取消信号
time.Sleep(10 * time.Second)
fmt.Println("Work canceled")
}
}
func main() {
// 打印当前时间
fmt.Println("Current time:", time.Now().Format(time.RFC1123))
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go doWork(ctx) // 在一个新的goroutine中执行耗时操作
// 等待超时或工作完成
<-ctx.Done()
fmt.Println("Main function: Work is done or canceled")
// 阻塞主线程一段时间,例如5秒
fmt.Println("Main thread will block for 5 seconds...")
time.Sleep(5 * time.Second)
// 阻塞结束后打印信息
fmt.Println("Main thread is unblocked.")
}
结果
发生主进程退出,强行结束子协程的问题
如何避免这样的问题
用sync.WaitGroup