1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. func main() {
    7. fmt.Println("run")
    8. doWork := func(done <-chan interface{}, pulseInterval time.Duration) (<-chan interface{}, <-chan time.Time) {
    9. heartbeat := make(chan interface{}) // 我们建立了一个发送心跳的 channel。我们把这个返回给 doWork
    10. results := make(chan time.Time)
    11. go func() {
    12. defer close(heartbeat)
    13. defer close(results)
    14. pulse := time.Tick(pulseInterval) // 我们设定心跳的间隔时间为我们接到的 pulseInterval。每隔一个 pulseInterval 的时长都会有一些东西读取这个 channel。
    15. workGen := time.Tick(2 * pulseInterval) // 这是另一个用来模拟滴答声的 channel。我们选择的持续时间大于 pulseInterval,这样我们就能看到从 goroutine 中发出的一些心跳。
    16. sendPulse := func() {
    17. select {
    18. case heartbeat <- struct{}{}:
    19. default: // 注意,这里我们加入了一个默认语句。我们必须时刻警惕这样一个事实:可能会没有人接收我们的心跳。从 goroutine 发出的信息是重要的,但心跳却不一定重要。
    20. }
    21. }
    22. sendResult := func(r time.Time) {
    23. for {
    24. select {
    25. case <-done:
    26. return
    27. case <-pulse: // 就像 done channel 一样,当你执行发出或接收时,你会需要包含一个发送心跳的分支。
    28. sendPulse()
    29. case results <- r:
    30. return
    31. }
    32. }
    33. }
    34. for {
    35. select {
    36. case <-done:
    37. return
    38. case <-pulse:
    39. sendPulse()
    40. case r := <-workGen:
    41. sendResult(r)
    42. }
    43. }
    44. }()
    45. return heartbeat, results
    46. }
    47. done := make(chan interface{})
    48. time.AfterFunc(10*time.Second, func() { close(done) })
    49. const timeout = 2 * time.Second
    50. heartbeat, results := doWork(done, timeout/2)
    51. for {
    52. select {
    53. case _, ok := <-heartbeat:
    54. if ok == false {
    55. return
    56. }
    57. fmt.Println("pulse")
    58. case r, ok := <-results:
    59. if ok == false {
    60. return
    61. }
    62. fmt.Printf("results %v\n", r.Second())
    63. case <-time.After(timeout):
    64. return
    65. }
    66. }
    67. }
    68. 输出:
    69. run
    70. pulse
    71. pulse
    72. results 57
    73. pulse
    74. pulse
    75. results 59
    76. pulse
    77. pulse
    78. results 1
    79. pulse
    80. pulse
    81. results 3
    82. pulse
    83. results 5