Merge pull request #468 from xushiwei/q

demo: ctxcancel
This commit is contained in:
xushiwei
2024-07-08 16:05:25 +08:00
committed by GitHub
2 changed files with 40 additions and 1 deletions

39
_demo/ctxcancel/ctx.go Normal file
View File

@@ -0,0 +1,39 @@
package main
import (
"context"
"fmt"
)
func main() {
// 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) <-chan int {
dst := make(chan int)
n := 1
go func() {
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
}
}
}

View File

@@ -127,7 +127,7 @@ func (p Program) Zero(t Type) Expr {
default: default:
panic("todo") panic("todo")
} }
case *types.Pointer: case *types.Pointer, *types.Signature, *types.Chan:
return Expr{llvm.ConstNull(t.ll), t} return Expr{llvm.ConstNull(t.ll), t}
case *types.Struct: case *types.Struct:
n := u.NumFields() n := u.NumFields()