zoukankan      html  css  js  c++  java
  • goroutine 上下文用法

    // 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在一个单独的goroutine中生成整数并将它们发送到返回的通道。

    //gen的调用方需要在使用生成的整数后取消上下文,以避免泄漏gen启动的内部goroutine。
    `package main

    import (
    "context"
    "fmt"
    )
    func main() {
    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
    	}
    }
    

    }`

    输出结果:
    1
    2
    3
    4
    5

  • 相关阅读:
    中英切换
    vue-cli3 关闭一直运行的 /sockjs-node/info?t= ...
    vue 深拷贝
    C++ 中 typename
    将博客搬至CSDN
    死锁及处理
    C 运算符优先级
    阻塞与非阻塞,同步与异步
    同步函数与异步函数
    C 结构体位域
  • 原文地址:https://www.cnblogs.com/DXGG-Bond/p/13563771.html
Copyright © 2011-2022 走看看