2021-04-12 19:32:51 +03:00
|
|
|
import context
|
|
|
|
|
|
|
|
// This example demonstrates the use of a cancelable context to prevent a
|
|
|
|
// routine leak. By the end of the example function, the routine started
|
|
|
|
// by gen will return without leaking.
|
|
|
|
fn test_with_cancel() {
|
|
|
|
// gen generates integers in a separate routine 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 routine started by gen.
|
2021-04-13 07:04:13 +03:00
|
|
|
gen := fn (ctx context.Context) chan int {
|
2021-04-12 19:32:51 +03:00
|
|
|
dst := chan int{}
|
2021-04-13 07:04:13 +03:00
|
|
|
go fn (ctx context.Context, dst chan int) {
|
|
|
|
mut v := 0
|
2021-04-12 19:32:51 +03:00
|
|
|
ch := ctx.done()
|
2021-04-13 07:04:13 +03:00
|
|
|
for {
|
2021-04-12 19:32:51 +03:00
|
|
|
select {
|
|
|
|
_ := <-ch {
|
|
|
|
// returning not to leak the routine
|
2021-04-13 07:04:13 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
dst <- v {
|
|
|
|
v++
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-04-13 07:04:13 +03:00
|
|
|
}(ctx, dst)
|
2021-04-12 19:32:51 +03:00
|
|
|
return dst
|
|
|
|
}
|
|
|
|
|
2021-04-13 07:04:13 +03:00
|
|
|
ctx := context.with_cancel(context.background())
|
2021-04-12 19:32:51 +03:00
|
|
|
defer {
|
2021-04-13 07:04:13 +03:00
|
|
|
context.cancel(ctx)
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|
|
|
|
|
2021-04-13 07:04:13 +03:00
|
|
|
ch := gen(ctx)
|
2021-04-12 19:32:51 +03:00
|
|
|
for i in 0 .. 5 {
|
|
|
|
v := <-ch
|
|
|
|
assert i == v
|
|
|
|
}
|
|
|
|
}
|