#context with cancel parent go routine cancel the child goroutine, when parent routine stops to consume more messages, it call context.Cancel() function to signal the child routine
funcmain() { // 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) <-chanint { dst := make(chanint) n := 1 gofunc() { 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 } } }
#context with value
we can pass some value from routines to routines, about the ‘key’, it’s not suggested using string data type directly
res := make(chanstring, 1) gofunc() { deferclose(res) for { select { case <-time.After(1 * time.Second): fmt.Println("overslept") res <- "working\n" case <-c.Done(): fmt.Println(c.Err()) // prints "context deadline exceeded" res <- "timeout\n" return } } }()