douzhu1188 2017-01-13 07:13
浏览 67
已采纳

在select {case:channel}中更改频道

I use a Ticker to execute tasks periodically, but I've got some problems when changing it. I'll change the ticker to a new one on receiving some messages and change the interval. Here's the sample code which will repro this problem:

package main

import (
    "fmt"
    "time"
)

type A struct {
    ticker *time.Ticker
}

func (a *A) modify() {
    a.ticker.Stop()
    a.ticker = time.NewTicker(time.Second)
}
func main() {
    a := new(A)
    a.ticker = time.NewTicker(time.Second)
    go func() {
        for {
            select {
            case <-a.ticker.C:
                fmt.Println("now")
                go a.modify()
                /*
                    default:
                        //fmt.Println("default")
                        time.Sleep(time.Millisecond * 100)
                */
            }
        }
    }()
    time.Sleep(time.Second * 60)
}

"now" will be printed only once. But it will be printed continously if I remove the "go", like this:

package main

import (
    "fmt"
    "time"
)

type A struct {
    ticker *time.Ticker
}

func (a *A) modify() {
    a.ticker.Stop()
    a.ticker = time.NewTicker(time.Second)
}
func main() {
    a := new(A)
    a.ticker = time.NewTicker(time.Second)
    go func() {
        for {
            select {
            case <-a.ticker.C:
                fmt.Println("now")
                a.modify()
                /*
                    default:
                        //fmt.Println("default")
                        time.Sleep(time.Millisecond * 100)
                */
            }
        }
    }()
    time.Sleep(time.Second * 60)
}

Also, if I leave the default clause un-commented, "now" can be printed continously. Can anyone explain how would this happen?

  • 写回答

1条回答 默认 最新

  • dongyan7851 2017-01-13 08:06
    关注

    The problem is that goroutine runs asynchronously. your code behave like this when using a.modify():

    1. get tick from a.ticker.C
    2. stop old ticker, and create new a.ticker.C
    3. wait for a.ticker.C using select

    In this case, newly created a.ticker.C in 2. is identical to channel waiting in 3.

    If you do 2. in goroutine. it may be done in following order

    1. get tick from a.ticker.C
    2. wait for a.ticker.C using select
    3. stop old ticker, and create new a.ticker.C

    In this case channel waiting in 2. is different from newly created channel in 3. . Since selecting channel is old one which is stopped, it never gets any tick.

    You can confirm this behavior inserting some fmt.Printf and watch for the address of a.ticker.C.

    func (a *A) modify() {
        a.ticker.Stop()
        fmt.Printf("ticker stopped: %p
    ", &a.ticker.C)
        a.ticker = time.NewTicker(time.Second)
        fmt.Printf("new ticker created: %p
    ", &a.ticker.C)
    }
    func main() {
        a := new(A)
        a.ticker = time.NewTicker(time.Second)
        go func() {
            for {
                fmt.Printf("waiting for ticker: %p
    ", &a.ticker.C)
                select {
            ....
    

    with a.modify():

    waiting for ticker: 0xc420010100
    ticker stopped: 0xc420010100
    new ticker created: 0xc420068000
    waiting for ticker: 0xc420068000
    ticker stopped: 0xc420068000
    new ticker created: 0xc420068080
    waiting for ticker: 0xc420068080
    

    with go a.modify():

    waiting for ticker: 0xc420010100
    waiting for ticker: 0xc420010100
    ticker stopped: 0xc420010100
    new ticker created: 0xc420066040
    

    you can see that with go a.modify() you are not waiting for a newly created channel.

    UPDATE for behavior of default:

    When using default: with go a.modify(), it will behave like this.

    1. wait for a.ticker.C, got tick, call go a.modify() which does 3.
    2. wait for a.ticker.C, got nothing, so fallback to default and sleep 100ms.
    3. stop old ticker, update a.ticker.C
    4. wait for a.ticker.C, got nothing, so fallback to default and sleep 100ms.
    5. wait for a.ticker.C, got nothing, so fallback to default and sleep 100ms.
    6. wait for a.ticker.C, got nothing, so fallback to default and sleep 100ms.

    .....

    1. wait for a.ticker.C, got tick, call go a.modify()

    The point is that for{} loop can keep on going even when you got nothing from a.ticker.C. You can confirm the behavior with same code.

    waiting ticker: 0xc420010100     <-- 1.
    now                              <-- 1.
    waiting ticker: 0xc420010100     <-- 2.
    default                          <-- 2.
    ticker stopped: 0xc420010100     <-- 3.
    new ticker created: 0xc420066240 <-- 3.
    waiting ticker: 0xc420066240     <-- 4.
    default                          <-- 4.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向