0


Go语学习笔记 - 处理超时问题 - Context使用 | 从零开始Go语言

学习笔记,写到哪是哪。

最近看了看go语言Context的使用,觉着很神奇也很便捷。

说到context,我在学习golang的时候看到很多库都用到了,简而言之,context可以处理多个goroutine之间的交互问题。类比于其他语言,你可能需要自己定义一个线程安全对象,通过线程安全对象来实现多个线程间的交互操作。golang直接有个默认包context,可以省掉每次定义的过程,还是很方便的。

具体关于Context的使用,我就不细说了,网上很多。

本文主要将我用context来实现一种超时场景的处理。

demo1

先使用context.WithTimeout方法来实现超时处理。

代码如下:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func handle() {
  8. //构建超时上下文
  9. _ctx, _cancel := context.WithTimeout(context.Background(), 5*time.Second)
  10. go work(_ctx)
  11. time.Sleep(6 * time.Second)
  12. _cancel()
  13. }
  14. //工作
  15. func work(ctx context.Context) {
  16. for {
  17. time.Sleep(1 * time.Second)
  18. select {
  19. case <-ctx.Done():
  20. fmt.Println("work done")
  21. default:
  22. fmt.Println("working")
  23. }
  24. }
  25. }
  26. func main() {
  27. handle()
  28. }

代码说明

1、 构建一个5秒超时的上下文传入goroutine,work方法轮询上下文状态。

执行结果

demo2

先使用context.WithDeadline方法来实现超时处理。

代码如下:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func handle1() {
  8. //构建超时上下文
  9. _ctx, _cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
  10. go work1(_ctx)
  11. time.Sleep(6 * time.Second)
  12. _cancel()
  13. }
  14. //工作1
  15. func work1(ctx context.Context) {
  16. for {
  17. time.Sleep(1 * time.Second)
  18. if _deadline, _a := ctx.Deadline(); _a {
  19. if time.Now().After(_deadline) {
  20. fmt.Println("after deadline")
  21. break
  22. }
  23. }
  24. select {
  25. case <-ctx.Done():
  26. fmt.Println("work done")
  27. default:
  28. fmt.Println("working")
  29. }
  30. }
  31. }
  32. func main() {
  33. handle1()
  34. }

代码说明

1、注意WithDeadline后面的时间参数方式,和WithTimeout不同。

2、这里在轮训前判断一下是否当前时间已经超过deadline,如果超过了直接跳出。

执行结果

小结

context还有很多用法,需要在项目中多使用,以后分享更多感受。


本文转载自: https://blog.csdn.net/zhiweihongyan1/article/details/126055893
版权归原作者 剑客阿良_ALiang 所有, 如有侵权,请联系我们删除。

“Go语学习笔记 - 处理超时问题 - Context使用 | 从零开始Go语言”的评论:

还没有评论