當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。