...占位
1, 例子理解
// from https://blog.csdn.net/u011957758/article/details/82948750package mainimport ( "context" "fmt" "math/rand" "time")/*1, main 和 chiHanBao 数据沟通 main 通过 chan eatNum 从函数ChiHanBao 中读取数据2, main 对 ChiHanBao的控制 main 通过 cancel 影响 ctx ,影响 <-ctx.Done() ,实现对ChiHanBao的控制*/func main() { ctx, cancel := context.WithCancel(context.Background()) eatNum := chiHanBao(ctx) for n := range eatNum { if n >= 10 { cancel() break } } fmt.Println("正在统计结果。。。") time.Sleep(1 * time.Second)}func chiHanBao(ctx context.Context) <-chan int { c := make(chan int) // 个数 n := 0 // 时间 t := 0 go func() { for { //time.Sleep(time.Second) select { case <-ctx.Done(): fmt.Printf("耗时 %d 秒,吃了 %d 个汉堡 \n", t, n) return case c <- n: incr := rand.Intn(5) n += incr if n >= 10 { n = 10 } t++ fmt.Printf("我吃了 %d 个汉堡\n", n) } } }() return c}
2,...和第一个例子差不多
func main() { // ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10)) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) chiHanBao(ctx) defer cancel()}func chiHanBao(ctx context.Context) { n := 0 for { select { case <-ctx.Done(): fmt.Println("stop \n") return default: incr := rand.Intn(5) n += incr fmt.Printf("我吃了 %d 个汉堡\n", n) } time.Sleep(time.Second) }}
总结
以上是内存溢出为你收集整理的go context全部内容,希望文章能够帮你解决go context所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)