Search code examples
goselecttimeout

it is quite common way to implement a timeout, why time.After is not working


the go code is show below, i try to print "result" by go routine. why "timeout" is not print after 3 second, but 10 second.since all the 10 "result" print.

package main
import "fmt"
import "time"


func main() {
  ch := make(chan string)
  go func() {
    for i:=0;i<10;i++ {
      time.Sleep(time.Second * 1)
      ch <- "result"
    }
      
  }()
  for {
    select {
    case res := <-ch:
        fmt.Println(res)
    case <-time.After(time.Second * 3):
        fmt.Println("timeout")
        return
    }
  }
}
/**
result
result
result
result
result
result
result
result
result
result
timeout
*/

Solution

  • In each for loop, after case res := <-ch, you create a new channel <-time.After(time.Second * 3).

    This fix maybe what you want:

        timeoutChan := time.After(time.Second * 3)
        for {
            select {
            case res := <-ch:
                fmt.Println(res)
            case <-timeoutChan:
                fmt.Println("timeout")
                return
            }
        }