股票代码告诉goroutine它是通过它的ticker.C停止了吗?

时间:2017-10-16 15:58:23

标签: go channel goroutine

package main
import "fmt"
import "time"

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
        fmt.Println("ticker stopped")
    }()
    time.Sleep(time.Second * 5)
    ticker.Stop()
    time.Sleep(time.Second * 5)
}

我想当我调用ticker.Stop()时,ticker.C应该告诉goroutine它已经结束了,所以for循环应该结束,但它看起来不像那样,字符串“ticker stopped”永远不会打印。

1 个答案:

答案 0 :(得分:1)

正如JimB指出的那样,time.Ticker的文档指定Stop()不会关闭频道,to prevent a read from the channel succeeding incorrectly.您最好的选择可能是退出频道。

package main

import "fmt"
import "time"

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    quit := make(chan struct{})
    go func() {
        for {
            select {
            case t := <-ticker.C:
                fmt.Println("Tick at", t)
            case <-quit:
                fmt.Println("ticker stopped")
                return
            }
        }
    }()
    time.Sleep(time.Second * 5)
    ticker.Stop()
    close(quit)
    time.Sleep(time.Second * 5)
}

https://play.golang.org/p/xTKNkMtdIf