1
0

test_context.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package TestCode
  2. import (
  3. "errors"
  4. "fmt"
  5. "golang.org/x/net/context"
  6. "time"
  7. )
  8. func baseHardWork(job interface{}) error {
  9. index := job.(int)
  10. println("Index:", index, "Start")
  11. time.Sleep(time.Second * 1)
  12. println("Index:", index, "End")
  13. return nil
  14. }
  15. func DoThings(ctx context.Context) error {
  16. const total = 10
  17. for i := 0; i < total; i++ {
  18. // 创建一个 chan 用于任务的中断和超时
  19. done := make(chan interface{}, 1)
  20. // 接收内部任务的 panic
  21. panicChan := make(chan interface{}, 1)
  22. go func() {
  23. defer func() {
  24. if p := recover(); p != nil {
  25. panicChan <- p
  26. }
  27. }()
  28. // 匹配对应的 Eps 去处理
  29. done <- baseHardWork(i)
  30. }()
  31. select {
  32. case errInterface := <-done:
  33. if errInterface != nil {
  34. println("Index:", i, "Error:", errInterface)
  35. }
  36. break
  37. case p := <-panicChan:
  38. // 遇到内部的 panic,向外抛出
  39. panic(p)
  40. case <-ctx.Done():
  41. {
  42. err := errors.New(fmt.Sprintf("cancel at index: %d", i))
  43. return err
  44. }
  45. }
  46. }
  47. return nil
  48. }
  49. func MainProcess() {
  50. ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
  51. defer cancel()
  52. go func() {
  53. err := DoThings(ctx)
  54. if err != nil {
  55. println("Error:", err.Error())
  56. }
  57. }()
  58. time.Sleep(5 * time.Second)
  59. cancel()
  60. }