等娘娘烘焙 發表於 2020-12-9 11:58:00

Go语言的context包从放弃到入门

<p></p><div class="toc"><div class="toc-container-header">目录</div><ul><li>一、Context包到底是干嘛用的</li><li>二、主协程退出通知子协程示例演示<ul><li>主协程通知子协程退出</li><li>主协程通知有子协程,子协程又有多个子协程</li></ul></li><li>三、Context包的核心接口和方法<ul><li>context接口</li><li>emptyCtx结构体<ul><li>Backgroud</li><li>TODO</li></ul></li><li>valueCtx结构体<ul><li>Value</li><li>WithValue</li><li>示例</li></ul></li><li>cancelCtx结构体<ul><li>WithCancel</li><li>示例</li></ul></li><li>timerCtx结构体<ul><li>WithDeadline</li><li>WithTimeout</li><li>示例</li></ul></li></ul></li><li>四、总结核心原理</li></ul></div><br>
以下内容由伟大的诗人、哲学家chenqionghe吐血传授,希望能帮助到你,谢谢~<p></p>
<h1 id="一context包到底是干嘛用的">一、Context包到底是干嘛用的</h1>
<p>我们会在用到很多东西的时候都看到context的影子,比如gin框架,比如grpc,这东西到底是做啥的?<br>
大家都在用,没几个知道这是干嘛的,知其然而不知其所以然</p>
<blockquote>
<p>谁都在CRUD,谁都觉得if else就完了,有代码能copy我也行,原理啥啥不懂不重要,反正就是一把梭</p>
</blockquote>
<p>原理说白了就是:</p>
<ol>
<li>当前协程取消了,可以通知所有由它创建的子协程退出</li>
<li>当前协程取消了,不会影响到创建它的父级协程的状态</li>
<li>扩展了额外的功能:超时取消、定时取消、可以和子协程共享数据</li>
</ol>
<h1 id="二主协程退出通知子协程示例演示">二、主协程退出通知子协程示例演示</h1>
<h2 id="主协程通知子协程退出">主协程通知子协程退出</h2>
<p>如下代码展示了,通过一个叫done的channel通道达到了这样的效果</p>
<pre><code>package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan string)

    //缓冲通道预先放置10个消息
    messages := make(chan int, 10)
    defer close(messages)
    for i := 0; i &lt; 10; i++ {
      messages &lt;- i
    }
    //启动3个子协程消费messages消息
    for i := 1; i &lt;= 3; i++ {
      go child(i, done, messages)
    }

    time.Sleep(3 * time.Second) //等待子协程接收一半的消息
    close(done) //结束前通知子协程
    time.Sleep(2 * time.Second) //等待所有的子协程输出
    fmt.Println("主协程结束")
}

//从messages通道获取信息,当收到结束信号的时候不再接收
func child(i int, done &lt;-chan string, messages &lt;-chan int) {
Consume:
    for {
      time.Sleep(1 * time.Second)
      select {
      case &lt;-done:
            fmt.Printf("[%d]被主协程通知结束...\n", i)
            break Consume
      default:
            fmt.Printf("[%d]接收消息: %d\n", i, &lt;-messages)
      }
    }
}
</code></pre>
<p>运行结束如下<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115235284-1236735018.png" alt="" loading="lazy"></p>
<p>这里,我们用一个channel的关闭做到了通知所有的消费到一半的子协程退出。<br>
问题来了,如果子协程又要启动它的子协程,这可咋整?</p>
<h2 id="主协程通知有子协程子协程又有多个子协程">主协程通知有子协程,子协程又有多个子协程</h2>
<p>这是个哲学问题,我们还是得建立一个叫done的channel来监测<br>
下面演示一下这种操作,再在每个child方法里启动多个job,如下<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115254639-1747491985.png" alt="" loading="lazy"></p>
<p>全量代码贴出来</p>
<pre><code>package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan string)

    //缓冲通道预先放置10个消息
    messages := make(chan int, 10)
    defer close(messages)
    for i := 0; i &lt; 10; i++ {
      messages &lt;- i
    }
    //启动3个子协程消费messages消息
    for i := 1; i &lt;= 3; i++ {
      go child(i, done, messages)
    }

    time.Sleep(3 * time.Second) //等待子协程接收一半的消息
    close(done) //结束前通知子协程
    time.Sleep(2 * time.Second) //等待所有的子协程输出
    fmt.Println("主协程结束")
}

//从messages通道获取信息,当收到结束信号的时候不再接收
func child(i int, done &lt;-chan string, messages &lt;-chan int) {
    newDone := make(chan string)
    defer close(newDone)
    go childJob(i, "a", newDone)
    go childJob(i, "b", newDone)

Consume:
    for {
      time.Sleep(1 * time.Second)
      select {
      case &lt;-done:
            fmt.Printf("[%d]被主协程通知结束...\n", i)
            break Consume
      default:
            fmt.Printf("[%d]接收消息: %d\n", i, &lt;-messages)
      }
    }
}

//任务
func childJob(parent int, name string, done &lt;-chan string) {
    for {
      time.Sleep(1 * time.Second)
      select {
      case &lt;-done:
            fmt.Printf("[%d-%v]被结束...\n", parent, name)
            return
      default:
            fmt.Printf("[%d-%v]执行\n", parent, name)
      }
    }
}
</code></pre>
<p>运行结果如下<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115304469-1984647477.png" alt="" loading="lazy"></p>
<p>问题来了,如果job里再启动自己的goroutine,这样没完没了的建立done的通道有点恶心,这时候context包就来了!</p>
<p>我们先把上面的代码改成context包的方式</p>
<pre><code>package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    //缓冲通道预先放置10个消息
    messages := make(chan int, 10)
    defer close(messages)
    for i := 0; i &lt; 10; i++ {
      messages &lt;- i
    }
    //启动3个子协程消费messages消息
    for i := 1; i &lt;= 3; i++ {
      go child(i, ctx, messages)
    }
    time.Sleep(3 * time.Second) //等待子协程接收一半的消息
    cancel() //结束前通知子协程
    time.Sleep(2 * time.Second) //等待所有的子协程输出
    fmt.Println("主协程结束")
}

//从messages通道获取信息,当收到结束信号的时候不再接收
func child(i int, ctx context.Context, messages &lt;-chan int) {
    //基于父级的context建立context
    newCtx, _ := context.WithCancel(ctx)
    go childJob(i, "a", newCtx)
    go childJob(i, "b", newCtx)

Consume:
    for {
      time.Sleep(1 * time.Second)
      select {
      case &lt;-ctx.Done():
            fmt.Printf("[%d]被主协程通知结束...\n", i)
            break Consume
      default:
            fmt.Printf("[%d]接收消息: %d\n", i, &lt;-messages)
      }
    }
}

//任务
func childJob(parent int, name string, ctx context.Context) {
    for {
      time.Sleep(1 * time.Second)
      select {
      case &lt;-ctx.Done():
            fmt.Printf("[%d-%v]被结束...\n", parent, name)
            return
      default:
            fmt.Printf("[%d-%v]执行\n", parent, name)
      }
    }
}
</code></pre>
<p>运行结果如下<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115320363-1653332763.png" alt="" loading="lazy"></p>
<p>可以看到,改成context包还是顺利的通过子协程退出了<br>
主要修改了几个地方,再ctx向下传递<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115326378-1520109390.png" alt="" loading="lazy"></p>
<p>基于上层context再构建当前层级的context<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115339876-827776852.png" alt="" loading="lazy"></p>
<p>监听context的退出信号,<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209115343705-1389596842.png" alt="" loading="lazy"></p>
<p>这就是context包的核心原理,链式传递context,基于context构造新的context</p>
<h1 id="三context包的核心接口和方法">三、Context包的核心接口和方法</h1>
<p>更多资料可以查看:Go语言设计与实现</p>
<h2 id="context接口">context接口</h2>
<p>context是一个接口,主要包含以下4个方法</p>
<ul>
<li>Deadline<br>
返回当前context任务被取消的时间,没有设定返回ok返回false</li>
<li>Done<br>
当绑定当前的context任务被取消时,将返回一个关闭的channel</li>
<li>Err<br>
Done返回的channel没有关闭,返回nil;<br>
Done返回的channel已经关闭,返回非空值表示任务结束的原因;<br>
context被取消,返回Canceled。<br>
context超时,DeadlineExceeded</li>
<li>Value<br>
返回context存储的键</li>
</ul>
<h2 id="emptyctx结构体">emptyCtx结构体</h2>
<p>实现了context接口,emptyCtx没有超时时间,不能取消,也不能存储额外信息,所以emptyCtx用来做根节点,一般用Background和TODO来初始化emptyCtx</p>
<h3 id="backgroud">Backgroud</h3>
<p>通常用于主函数,初始化以及测试,作为顶层的context</p>
<h3 id="todo">TODO</h3>
<p>不确定使用什么用context的时候才会使用</p>
<h2 id="valuectx结构体">valueCtx结构体</h2>
<pre><code>type valueCtx struct{ Context key, val interface{} }
</code></pre>
<p>valueCtx利用Context的变量来表示父节点context,所以当前context继承了父context的所有信息<br>
valueCtx还可以存储键值。</p>
<h3 id="value">Value</h3>
<pre><code>func (c *valueCtx) Value(key interface{}) interface{} {
    if c.key == key {
      return c.val
    }
    return c.Context.Value(key)
}
</code></pre>
<p>可以用来获取当前context和所有的父节点存储的key</p>
<blockquote>
<p>如果当前的context不存在需要的key,会沿着context链向上寻找key对应的值,直到根节点</p>
</blockquote>
<h3 id="withvalue">WithValue</h3>
<p>可以向context添加键值</p>
<pre><code>func WithValue(parent Context, key, val interface{}) Context {
    if key == nil {
      panic("nil key")
    }
    if !reflect.TypeOf(key).Comparable() {
      panic("key is not comparable")
    }
    return &amp;valueCtx{parent, key, val}
}
</code></pre>
<p>添加键值会返回创建一个新的valueCtx子节点</p>
<h3 id="示例">示例</h3>
<pre><code>package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx := context.WithValue(context.Background(), "top", "root")

    //第一层
    go func(parent context.Context) {
      ctx = context.WithValue(parent, "cqh", "chenqionghe")
      //第二层
      go func(parent context.Context) {
            ctx = context.WithValue(parent, "xsfz", "雪山飞猪")
            //第三层
            go func(parent context.Context) {
                //可以获取所有的父类的值
                fmt.Println(ctx.Value("top"))
                fmt.Println(ctx.Value("cqh"))
                fmt.Println(ctx.Value("xsfz"))
                //不存在
                fmt.Println(ctx.Value("xxxx"))
            }(ctx)
      }(ctx)
    }(ctx)
    time.Sleep(1 * time.Second)
    fmt.Println("end")
}
</code></pre>
<p>运行结果<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209164357962-1351246205.png" alt="" loading="lazy"><br>
可以看到,子context是可以获取所有父级设置过的key</p>
<h2 id="cancelctx结构体">cancelCtx结构体</h2>
<pre><code>type cancelCtx struct {
    Context
    mu sync.Mutex
    done chan struct{}
    children mapstruct{}
    err error
}
type canceler interface {
    cancel(removeFromParent bool, err error)
    Done() &lt;-chan struct{}
}

</code></pre>
<p>和valueCtx类似,有一个context做为父节点,<br>
变量done表示一个channel,用来表示传递关闭;<br>
children表示一个map,存储了当前context节点为下的子节点<br>
err用来存储错误信息表示任务结束的原因</p>
<h3 id="withcancel">WithCancel</h3>
<p>用来创建一个可取消的context,返回一个context和一个CancelFunc,调用CancelFunc可以触发cancel操作。</p>
<h3 id="示例-1">示例</h3>
<pre><code>package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    //第一层
    go func(parent context.Context) {
      ctx, _ := context.WithCancel(parent)
      //第二层
      go func(parent context.Context) {
            ctx, _ := context.WithCancel(parent)
            //第三层
            go func(parent context.Context) {
                waitCancel(ctx, 3)
            }(ctx)
            waitCancel(ctx, 2)
      }(ctx)
      waitCancel(ctx, 1)
    }(ctx)
    time.Sleep(5 * time.Second)
    cancel()
    time.Sleep(1 * time.Second)
}

func waitCancel(ctx context.Context, i int) {
    for {
      time.Sleep(time.Second)
      select {
      case &lt;-ctx.Done():
            fmt.Printf("%d end\n", i)
            return
      default:
            fmt.Printf("%d do\n", i)
      }
    }
}
</code></pre>
<p>运行结果<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209171828697-833664711.png" alt="" loading="lazy"><br>
可以看到,在外边调用cancel方法,所有的子goroutine都已经收到停止信号</p>
<h2 id="timerctx结构体">timerCtx结构体</h2>
<p>timerCtx是基于cancelCtx的context精英,是一种可以定时取消的context,过期时间的deadline不晚于所设置的时间d</p>
<h3 id="withdeadline">WithDeadline</h3>
<p>返回一个基于parent的可取消的context,并且过期时间deadline不晚于所设置时间d</p>
<h3 id="withtimeout">WithTimeout</h3>
<p>创建一个定时取消context,和WithDeadline差不多,WithTimeout是相对时间</p>
<h3 id="示例-2">示例</h3>
<pre><code>package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    //第一层
    go func(parent context.Context) {
      ctx, _ := context.WithCancel(parent)
      //第二层
      go func(parent context.Context) {
            ctx, _ := context.WithCancel(parent)
            //第三层
            go func(parent context.Context) {
                waitCancel(ctx, 3)
            }(ctx)
            waitCancel(ctx, 2)
      }(ctx)
      waitCancel(ctx, 1)
    }(ctx)

    &lt;-ctx.Done()

    time.Sleep(1 * time.Second)
}

func waitCancel(ctx context.Context, i int) {
    for {
      time.Sleep(time.Second)
      select {
      case &lt;-ctx.Done():
            fmt.Printf("%d end\n", i)
            return
      default:
            fmt.Printf("%d do\n", i)
      }
    }
}
</code></pre>
<p>运行结果<br>
<img src="https://img2020.cnblogs.com/blog/662544/202012/662544-20201209172240107-343250904.png" alt="" loading="lazy"></p>
<p>可以看到,虽然我们没有调用cancel方法,5秒后自动调用了,所有的子goroutine都已经收到停止信号</p>
<h1 id="四总结核心原理">四、总结核心原理</h1>
<ol>
<li>Done方法返回一个channel</li>
<li>外部通过调用&lt;-channel监听cancel方法</li>
<li>cancel方法会调用close(channel)<br>
当调用close方法的时候,所有的channel再次从通道获取内容,会返回零值和false</li>
</ol>
<pre><code>res,ok := &lt;-done:
</code></pre>
<ol start="4">
<li>过期自动取消,使用了time.AfterFunc方法,到时调用cancel方法</li>
</ol>
<pre><code>c.timer = time.AfterFunc(dur, func() {
   c.cancel(true, DeadlineExceeded)
})
</code></pre>
<p>授人以渔不如授人以渔,知其然也知其所以然,让我们共同构建美丽新世界,让人与自然更加和谐,就是这样,giao~</p><br><br>
来源:https://www.cnblogs.com/chenqionghe/p/14107790.html
頁: [1]
查看完整版本: Go语言的context包从放弃到入门