ctx_cancel.go 442 B

123456789101112131415161718192021222324252627282930313233343536
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. var c chan bool
  8. func init() {
  9. c = make(chan bool, 10)
  10. for i := 0; i < 10; i++ {
  11. c <- true
  12. }
  13. }
  14. func main() {
  15. ctx, cancel := context.WithCancel(context.Background())
  16. close(c)
  17. println(1)
  18. cancel()
  19. println(2)
  20. exit:
  21. for {
  22. select {
  23. case data, ok := <-c:
  24. fmt.Println(data, ok)
  25. time.Sleep(1 * time.Second)
  26. case <-ctx.Done():
  27. println(3)
  28. break exit
  29. }
  30. }
  31. println(4)
  32. }