dongliao1949 2018-05-25 04:06
浏览 246

为什么golang ticker.Stop()在tickerTest1中不起作用?

result of two testTicker

I know the Stop function can not close the channel. I am just confused with the two different results of tickerTest1 and tickerTest2.

package main

import (
    "time"
    "log"
)

func tickerTest1() {
    ticker := *time.NewTicker(time.Second)
    count := 0
    go func() {
        time.Sleep(3*time.Second)
        ticker.Stop()
    }()
    for range ticker.C {
        count ++
        log.Println("tickerTest1:", count)
    }
}

func tickerTest2() {
    ticker := time.NewTicker(time.Second)
    count := 0
    go func() {
        time.Sleep(3*time.Second)
        ticker.Stop()
    }()
    for range ticker.C {
        count ++
        log.Println("tickerTest2:", count)
    }
}

func main() {
    go tickerTest1()
    tickerTest2()
}
  • 写回答

1条回答 默认 最新

  • douwen1937 2018-05-25 06:37
    关注

    tickerTest2() works as expected, so let's examine tickerTest1().

    time.NewTicker() returns a pointer value, a value of type *time.Ticker. This already hints you should use it as that: as a pointer (and should not dereference it).

    Yet, you dereference it by using the indirection operator:

    ticker := *time.NewTicker(time.Second)
    

    By dereferencing it,ticker will be of type time.Ticker, a non-pointer type. And its value will be a copy of the value pointed by the pointer that NewTicker() returns.

    This alone wouldn't be a problem, because Go automatically takes the address of ticker whenever you call a method with pointer receiver on it (such as Ticker.Stop()). But the address that is passed as the receiver will be the address of this ticker variable, and any method that modifies the time.Ticker struct will only modify this distinct copy, and not the time.Ticker value that is pointed by the return value of the NewTicker() function.

    So in effect, you only stop the copy Ticker stored in the ticker variable, and not the original Ticker that was returned by NewTicker() and which is actually sending the values on the channel. That remains unstopped.

    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗