diff options
author | Indrajith K L | 2022-12-03 17:00:20 +0530 |
---|---|---|
committer | Indrajith K L | 2022-12-03 17:00:20 +0530 |
commit | f5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch) | |
tree | 2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/vlib/context/cancel_test.v | |
download | cli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.tar.gz cli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.tar.bz2 cli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.zip |
Diffstat (limited to 'v_windows/v/vlib/context/cancel_test.v')
-rw-r--r-- | v_windows/v/vlib/context/cancel_test.v | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/v_windows/v/vlib/context/cancel_test.v b/v_windows/v/vlib/context/cancel_test.v new file mode 100644 index 0000000..6b9fdaa --- /dev/null +++ b/v_windows/v/vlib/context/cancel_test.v @@ -0,0 +1,42 @@ +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. + gen := fn (ctx context.Context) chan int { + dst := chan int{} + go fn (ctx context.Context, dst chan int) { + mut v := 0 + ch := ctx.done() + for { + select { + _ := <-ch { + // returning not to leak the routine + return + } + dst <- v { + v++ + } + } + } + }(ctx, dst) + return dst + } + + ctx := context.with_cancel(context.background()) + defer { + context.cancel(ctx) + } + + ch := gen(ctx) + for i in 0 .. 5 { + v := <-ch + assert i == v + } +} |