2021-09-23 14:55:04 +03:00
|
|
|
// vtest retry: 3
|
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-10-11 15:41:31 +03:00
|
|
|
gen := fn (mut ctx context.Context) chan int {
|
2021-04-12 19:32:51 +03:00
|
|
|
dst := chan int{}
|
2021-10-11 15:41:31 +03:00
|
|
|
go fn (mut ctx context.Context, dst chan int) {
|
2021-04-13 07:04:13 +03:00
|
|
|
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-10-11 15:41:31 +03:00
|
|
|
}(mut ctx, dst)
|
2021-04-12 19:32:51 +03:00
|
|
|
return dst
|
|
|
|
}
|
|
|
|
|
2021-10-11 15:41:31 +03:00
|
|
|
mut background := context.background()
|
|
|
|
mut b := &background
|
|
|
|
mut ctx, cancel := context.with_cancel(mut b)
|
2021-04-12 19:32:51 +03:00
|
|
|
defer {
|
2021-09-27 17:52:20 +03:00
|
|
|
cancel()
|
2021-04-12 19:32:51 +03:00
|
|
|
}
|
|
|
|
|
2021-10-11 15:41:31 +03:00
|
|
|
mut mut_ctx := ctx
|
|
|
|
mut ctx2 := &mut_ctx
|
|
|
|
ch := gen(mut ctx2)
|
2021-04-12 19:32:51 +03:00
|
|
|
for i in 0 .. 5 {
|
|
|
|
v := <-ch
|
|
|
|
assert i == v
|
|
|
|
}
|
|
|
|
}
|