在select语句中更改一个通道的写法是:select{case:通道}。

huangapple go评论81阅读模式
英文:

Change a channel in select{case:channel}

问题

我使用一个 Ticker 来定期执行任务,但在更改它时遇到了一些问题。我会在接收到一些消息时将 Ticker 更改为新的,并更改时间间隔。以下是一个示例代码,可以重现这个问题:

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"。但是如果我移除 "go",就会连续打印,像这样:

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)
}

另外,如果我取消注释默认的分支,"now" 就会连续打印。有人能解释一下为什么会这样吗?

英文:

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 (
    &quot;fmt&quot;
    &quot;time&quot;
)

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 &lt;-a.ticker.C:
                fmt.Println(&quot;now&quot;)
                go a.modify()
                /*
                    default:
                        //fmt.Println(&quot;default&quot;)
                        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 (
    &quot;fmt&quot;
    &quot;time&quot;
)

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 &lt;-a.ticker.C:
                fmt.Println(&quot;now&quot;)
                a.modify()
                /*
                    default:
                        //fmt.Println(&quot;default&quot;)
                        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

得分: 0

问题在于goroutine以异步方式运行。
当使用a.modify()时,你的代码的行为如下:

  1. a.ticker.C获取tick。
  2. 停止旧的ticker,并创建新的a.ticker.C
  3. 使用select等待a.ticker.C

在这种情况下,第2步中新创建的a.ticker.C与第3步中等待的通道是相同的。

如果你在goroutine中执行第2步,可能会按照以下顺序执行:

  1. a.ticker.C获取tick。
  2. 使用select等待a.ticker.C
  3. 停止旧的ticker,并创建新的a.ticker.C

在这种情况下,第2步中等待的通道与第3步中新创建的通道是不同的。
由于选择的通道是已停止的旧通道,它永远不会收到任何tick。

你可以通过插入一些fmt.Printf并观察a.ticker.C的地址来确认这种行为。

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

func main() {
    a := new(A)
    a.ticker = time.NewTicker(time.Second)
    go func() {
        for {
            fmt.Printf("waiting for ticker: %p\n", &a.ticker.C)
            select {
            ....

使用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

使用go a.modify()的输出结果如下:

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

你可以看到,使用go a.modify()时,你不会等待新创建的通道。

关于默认行为的更新:

当在go a.modify()中使用default:时,它的行为如下:

  1. 等待a.ticker.C,收到tick,调用go a.modify()执行第3步。
  2. 等待a.ticker.C,没有收到任何内容,所以回退到默认情况并休眠100毫秒。
  3. 停止旧的ticker,更新a.ticker.C
  4. 等待a.ticker.C,没有收到任何内容,所以回退到默认情况并休眠100毫秒。
  5. 等待a.ticker.C,没有收到任何内容,所以回退到默认情况并休眠100毫秒。
  6. 等待a.ticker.C,没有收到任何内容,所以回退到默认情况并休眠100毫秒。

......

  1. 等待a.ticker.C,收到tick,调用go a.modify()

关键是for{}循环可以继续进行,即使从a.ticker.C中没有收到任何内容。
你可以使用相同的代码确认这种行为。

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.
英文:

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(&quot;ticker stopped: %p\n&quot;, &amp;a.ticker.C)
	a.ticker = time.NewTicker(time.Second)
	fmt.Printf(&quot;new ticker created: %p\n&quot;, &amp;a.ticker.C)
}
func main() {
	a := new(A)
	a.ticker = time.NewTicker(time.Second)
	go func() {
		for {
			fmt.Printf(&quot;waiting for ticker: %p\n&quot;, &amp;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     &lt;-- 1.
now                              &lt;-- 1.
waiting ticker: 0xc420010100     &lt;-- 2.
default                          &lt;-- 2.
ticker stopped: 0xc420010100     &lt;-- 3.
new ticker created: 0xc420066240 &lt;-- 3.
waiting ticker: 0xc420066240     &lt;-- 4.
default                          &lt;-- 4.

huangapple
  • 本文由 发表于 2017年1月13日 15:13:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41629227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定