1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

context: add a new context module, based on Golang's context, intended to be used in webservers (#9563)

This commit is contained in:
Ulises Jeremias Cornejo Fandos
2021-04-12 13:32:51 -03:00
committed by GitHub
parent b54188dfea
commit 07a6f4e445
10 changed files with 778 additions and 1 deletions

View File

@@ -0,0 +1,39 @@
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 (mut ctx context.CancelerContext) chan int {
dst := chan int{}
go fn (mut ctx context.CancelerContext, dst chan int) {
ch := ctx.done()
loop: for i in 0 .. 5 {
select {
_ := <-ch {
// returning not to leak the routine
break loop
}
dst <- i {}
}
}
}(mut ctx, dst)
return dst
}
mut ctx := context.with_cancel(context.background())
defer {
context.cancel(mut ctx)
}
ch := gen(mut ctx)
for i in 0 .. 5 {
v := <-ch
assert i == v
}
}