Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Never ending Ticker in Golang works only 2 times

Tags:

go

I'm trying to make a channel with never ending ticker, but it works only 2 times.

Could you help me to understand where is the problem?

Code:

package main 

import (
"fmt"
"time"
) 

var mark = [2]float64{8.9876, 762.098568}

func tick(out chan <- [2]float64){

    c := time.NewTicker(time.Millisecond *500)
    for range c.C{
        out <- mark
    }
}

func main() {

    fmt.Println("Start")

    md := make(chan [2]float64)
    go tick(md)

    for range <-md{
        fmt.Println(<-md)
    }
}

Output:

Start
[8.9876 762.098568]
[8.9876 762.098568]

Example: https://play.golang.org/p/P2FaUwbW-3

like image 333
moneyzmey Avatar asked Aug 17 '17 17:08

moneyzmey


1 Answers

This:

for range <-md{

is not the same as:

for range md{

The latter ranges over the channel (what you want), while the former ranges over the value received from the channel when the loop starts, which happens to be a two-element array, hence the two executions. You're also ignoring the value received from the channel in the for statement, and reading from it again in the loop body, ignoring every other message on the channel (though this makes no difference in the example, since every value is identical, it would make a significant difference in practice). What you really want is:

for foo := range md{
    fmt.Println(foo)
}

Here's a working version of your playground example, slightly modified to avoid "program took too long" errors because in its current form it never stops: https://play.golang.org/p/RSUJFvluU5

like image 67
Adrian Avatar answered Oct 02 '22 19:10

Adrian