2016-01-20 52 views
2

我正在使用goroutines /频道。 这是我的代码。 为什么超时情况没有得到执行?Golang超时未与频道执行

func main() { 
    c1 := make(chan int, 1) 

    go func() { 
     for { 
      time.Sleep(1500 * time.Millisecond) 
      c1 <- 10 
     } 
    }() 

    go func() { 
     for { 
      select { 
      case i := <-c1: 
       fmt.Println(i) 
      case <-time.After(2000 * time.Millisecond): 
       fmt.Println("TIMEOUT") // <-- Not Executed 
      } 
     } 
    }() 

    fmt.Scanln() 
} 

回答

2

您超时不会发生,因为你够程之一,每1.5秒对你c1通道发送的值(左右)反复,如果没有要接收值只会发生在您超时从c1持续2秒。

一旦值从c1接收时,在再次执行select一个time.After()呼叫将被制成,其返回在其上的值将只2秒钟之后发送一个新通道下一次迭代。来自前一个select执行的超时通道将被丢弃,不再使用。

要2秒后接收超时,创建超时信道只有一次,例如:

timeout := time.After(2000 * time.Millisecond) 
for { 
    select { 
    case i := <-c1: 
     fmt.Println(i) 
    case <-timeout: 
     fmt.Println("TIMEOUT") // Will get executed after 2 sec 
    } 
} 

输出:

10 
TIMEOUT 
10 
10 
10 
...