context是一个用来通信的信号发生器
比如两个哑巴去打水,压水井在小屋里面,出水口在小屋外面,一个哑巴在里面压水,另外一个在外面接水,为了不浪费,希望接水的哑巴能及时通知压水的哑巴停止压水。
问题:如何让接水哑巴及时通知压水哑巴停止压水
解决方法:一根绳子,两头栓着两个哑巴,当接水的哑巴需要停止时,拉绳子,压水的哑巴就会感知到,停止压水
具体流程
获取一个绳子,这个绳子有两个功能, 可以被拽,可以被感知到正在被拽
压水的哑巴带着绳子一头进屋,开始压水,同时要感受绳子
外面接水的哑巴接水
当接够了,拽绳子
压水哑巴停止压水
package main
import (
"context"
"fmt"
)
func main() {
// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
break
}
}
}