当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO WithCancel用法及代码示例

GO语言"context"包中"WithCancel"函数的用法及代码示例。

用法:

func WithCancel(parent Context)(ctx Context, cancel CancelFunc)

WithCancel 返回具有新完成通道的父级副本。返回的上下文的完成通道在调用返回的取消函数或父上下文的完成通道关闭时关闭,以先发生者为准。

取消此上下文会释放与其关联的资源,因此代码应在此上下文中运行的操作完成后立即调用取消。

例子:

这个例子演示了使用可取消上下文来防止 goroutine 泄漏。在示例函数结束时,由 gen 启动的 goroutine 将返回而不会泄漏。

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
        }
    }
}

输出:

1
2
3
4
5

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 WithCancel。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。