R
R
raiboon2015-05-26 18:33:11
go
raiboon, 2015-05-26 18:33:11

What's going on here?

for {
    select {
    case res := <-c1:
      fmt.Println(res)
    case <-time.After(time.Second * 10):
      break
    case <-time.After(time.Second * 1):
      fmt.Println("timeout 1")

    }

  }

Why do we never go to the second branch? What's going on here?
UPD These are my games with an example - https://gobyexample.com/non-blocking-channel-operations , I just added another branch to the first select.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SilentFl, 2015-05-28
@raiboon

We don't go to the second branch because time.After creates a channel for us. Accordingly, at each iteration, the signal from time.After(1*time.Second) comes first, after which the next iteration of the loop occurs, and both time channels are recreated. Move time.After(10*time.Second) before the loop so that it doesn't recreate every iteration, and you'll be happy. like this:

package main

import (
  "fmt"
  "time"
)

func main() {
  c1 := make(chan struct{}, 10)
  time_limit := time.After(time.Second * 10)
Label1:
  for {
    select {
    case res := <-c1:
      fmt.Println(res)
    case <-time_limit:
      fmt.Println("time limit")
      break Label1
    case <-time.After(time.Second * 1):
      fmt.Println("timeout 1")
    }
  }
}

Note - we need Label1 here in due to the fact that the compiler regards break as part of select (because break is located first in select, and only then in for). The syntax break [label_name] allows you to specify who to break But personally ,
I don’t like this label at all (it gives off some kind of smell, as they returned in the 70s, and look goto will come out somewhere), and I would write this code like this:
package main

import (
  "fmt"
  "time"
)

func main() {
  c1 := make(chan struct{}, 10)
  time_limit := time.After(time.Second * 10)
  func() {
    for {
      select {
      case res := <-c1:
        fmt.Println(res)
      case <-time_limit:
        fmt.Println("time_limit")
        return
      case <-time.After(time.Second * 1):
        fmt.Println("timeout 1")
      }
    }
  }()  //просто анонимная функция
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question